简体   繁体   English

遍历字典,在python中列出

[英]Iterating through a dict, list in python

Now that I know how to iterate through a dict, I need to know how to iterate through a list and be able to print each customer, account and transaction. 既然我知道如何遍历字典,那么我需要知道如何遍历列表并能够打印每个客户,帐户和交易。 I have 3 classes Customer, Account, and Transaction. 我有3类客户,帐户和交易。 Within the Customer class, I put a list to hold Account objects and within the Account class, I have a list to hold Transaction objects. 在Customer类中,我放置了一个列表来保存Account对象,在Account类中,我有一个列表来保存Transaction对象。 Near the end of this code, I have a for loop iterating through the map, but when I try to iterate through the list, it doesn't seem to work. 在这段代码的结尾处,我有一个遍历map的for循环,但是当我尝试遍历列表时,它似乎不起作用。 It is most likely through my own error. 这很可能是由于我自己的错误。

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())

If you need more info, let me know. 如果您需要更多信息,请告诉我。 I need it to print each customer (which is within the dict) and every Account associated with that customer. 我需要它来打印每个客户(位于dict之内)和与该客户关联的每个帐户。 In the future I will need every transaction associated with that account. 将来,我将需要与该帐户关联的每笔交易。 I did it in Java (and it works) as follows: 我在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

Your help is much appreciated 非常感谢您的帮助

Iterating over a dict 's items: 遍历dict的项目:

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

Iterating over a dict 's keys: 遍历dict的键:

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

Iterating over a dict 's values: 遍历dict的值:

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

Iterating over a list : 遍历一个list

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

Note(s): 笔记):

  • DO NOT name your variables dict or list as they shadow the builtins and could cause you problems. 不要命名您的变量dictlist因为它们会掩盖内置函数并可能导致您出现问题。

Check out this line of code: 查看以下代码行:

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

You can't define key1 with a reference to key1 你不能定义key1与参考key1

To iterate through a list , you can do the following: 要遍历列表 ,您可以执行以下操作:

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

for item in a:
    print item

1
2
3
4
5

the word 'item' above was arbitrary, I could have used pretty much anything: 上面的“项目”一词是任意的,我几乎可以使用任何东西:

for i in a:
    print i+1

2
3
4
5
6

but essentially, it's: 但实际上,它是:

for element in listname:
    do something

There are other ways, but here are some docs: http://www.diveintopython.net/file_handling/for_loops.html 还有其他方法,但是这里有一些文档: http : //www.diveintopython.net/file_handling/for_loops.html

To iterate over a dict 遍历字典

you can do: 你可以做:

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...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM