简体   繁体   中英

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. 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. 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. 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. In the future I will need every transaction associated with that account. I did it in Java (and it works) as follows:

        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:

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

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

Iterating over a dict 's values:

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

Iterating over a 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.

Check out this line of code:

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

You can't define key1 with a reference to 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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