通过dict迭代,在python中列出

时间:2013-12-16 15:52:00

标签: java python list dictionary

现在我知道如何遍历dict,我需要知道如何遍历列表并能够打印每个客户,帐户和事务。我有3个类Customer,Account和Transaction。在Customer类中,我放置一个列表来保存Account对象,在Account类中,我有一个列表来保存Transaction对象。在这段代码的末尾,我有一个for循环遍历地图,但是当我尝试迭代列表时,它似乎不起作用。这很可能是由于我自己的错误。

class Customer(object):
'''Main Constructor'''
def__init__(self,CNumber=1,CName="A",CAddress="A",CCity="A",CState="A",CZipCode=1,CPhone="1",Account=[]):
    self.CNumber = CNumber
    self.CName = CName
    self.CAddress = CAddress
    self.CCity = CCity
    self.CState = CState
    self.CZipCode = CZipCode
    self.CPhone = CPhone
    self.Account = Account

dict = {}
c = Customer.Customer("1111","Jake","Main St","Happy Valley","CA","96687","8976098765")
dict[c.getCNumber()] = c
c = Customer.Customer("2222","Paul","3342 CherrySt","Seatle","WA","98673","9646745678")
dict[c.getCNumber()] = c

a = Account.Account("1111",True,0.00,500.00)
dict[c.getCNumber()].AddAccount(a)
a = Account.Account("2222",True,0.00,500.00)
dict[c.getCNumber()].AddAccount(a)
a = Account.Account("3333",False,0.02,10000.00)
dict[c.getCNumber()].AddAccount(a)
a = Account.Account("4444",False,0.02,10000.00)
dict[c.getCNumber()].AddAccount(a)

for key in sorted(dict.keys()):
    print("***Customer***")
    print("Customer Number: " + dict[key].getCNumber())
    print(dict[key].getCName())
    print(dict[key].getCAddress())
    print(dict[key].getCCity() + ", " + dict[key].getCState() + " " + dict[key].getCZipCode())
    for key1 in dict[key].getAccount()[key1]:
        print("\t***Account***")
        print("\tAccount Number: " + a.getANumber())
        print("\t" + a.getAType())
        print("\t" + a.getAInterestRate())

如果您需要更多信息,请与我们联系。我需要它来打印每个客户(在dict中)和与该客户相关联的每个帐户。将来,我将需要与该帐户关联的每笔交易。我在Java中做了它(它的工作原理)如下:

        for (Customer c : customerMap.values()) {
        // Print the customer name, address, etc.
        System.out.println("\n**********Customer**********");
        System.out.println("Customer Number: " + c.getCustomerNumber());
        System.out.println(c.getCustomerName());
        System.out.println(c.getCustomerAddress());
        System.out.println(c.getCustomerCity() + ", "
                + c.getCustomerState() + " " + c.getCustomerZipCode());
        System.out.println(c.getCustomerPhone());
        for (Account a : c.getAllAccounts()) {
            // Print the account balance, id, type
            System.out.println("\t**********Account**********");
            System.out.println("\tAccount Number: " + a.getAccountNumber());
            if (a.getAccountType() == true) {
                System.out.println("\tAccount Type: Checking");
            } else {
                System.out.println("\tAccount Type: Savings");
            }
            System.out.println("\tAccount Balance: " + a.getBalance());
            System.out.println("\tInterest Rate: " + a.getInterestRate());
            for (Transaction t : a.getAllTransactions()) {
                // Go through the transactions of this account
                System.out.println("\t\t**********Transactions**********");
                System.out.println("\t\tTransaction Date: " + t.getDate());
                System.out.println("\t\tTransaction Amount: "
                        + t.getAmount());
                if (t.getDebitOrCredit() == true) {
                    System.out.println("\t\tDebit or Credit: Credit");
                } else {
                    System.out.println("\t\tDebit or Credit: Debit");
                }
                System.out.println("\t\tMemo: " + t.getMemo());

            }// for
        }// for
    }// for

非常感谢您的帮助

3 个答案:

答案 0 :(得分:3)

dict个项目进行迭代:

>>> d = {"a": 1, "b": 2, "c": 3}
>>> for k, v in d.items():
...     print "{}={}".format(k, v)
... 
a=1
c=3
b=2

迭代dict个键:

>>> for k in d.keys():
...     print k
... 
a
c
b

迭代dict的值:

>>> for v in d.values():
...     print v
... 
1
3
2

迭代list

>>> xs = [1, 2, 3]
>>> for x in xs:
...     print x
... 
1
2
3
>>> 

注意(S):

  • 不要将变量命名为dictlist,因为它们会影响内置组件并导致问题。

答案 1 :(得分:0)

查看以下代码:

    for key1 in dict[key].getAccount()[key1]:

您无法通过引用key1

来定义key1

答案 2 :(得分:0)

要遍历列表 ,您可以执行以下操作:

a = [1,2,3,4,5]

for item in a:
    print item

1
2
3
4
5

上面的“项目”一词是任意的,我几乎可以使用任何东西:

for i in a:
    print i+1

2
3
4
5
6

但基本上是:

for element in listname:
    do something

还有其他方法,但这里有一些文档:http://www.diveintopython.net/file_handling/for_loops.html

迭代字典

你可以这样做:

for key in d.keys(): # iterates through a list of the dict d's keys
    some code..

for value in d.values(): #iterates through a list of dict d's values
    some code..

for key, value in d.items(): #iterates through a list of key/value pairs from d
    code code...