user3106444
user3106444

Reputation: 83

Iterating a Dictionary in Python

When I try to iterate this Dictionary, it only prints out twice the customer with "2222" as the key. I have no idea why this is happening. In the past I tried to use different variables for the customer c1 and c2 (instead of just c) but that defeated the purpose of using a for loop to print the dictionary.

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

for key in Dict.keys():
  print("***Customer***")
  print("Customer Number: " + c.getCNumber)

This prints:

***Customer***
Customer Number: 2222
***Customer***
Customer Number: 2222

How do I get it to iterate and have customer 1111 first, then customer 2222 second?

Upvotes: 2

Views: 119

Answers (3)

Kracekumar
Kracekumar

Reputation: 20419

.keys isn't required.

Python 2

In [127]: d = {'a': 1, 'b': 2}

In [128]: for key in d:
.....:     print(key)
.....:
a
b

Python 3

In [34]: d = {'a': 1, 'b': 2}

In [35]: for key in d:
....:     print(key)
....:
a
b

Looping over dict gives key.

Upvotes: 1

aga
aga

Reputation: 29416

That's exactly what you told your loop to do: traverse a keyset, and for every key in dictionary print a number of c variable. Change your loop like so:

for key in Dict.keys():
   print("***Customer***")
   print("Customer Number: " + Dict[key].getCNumber())

I believe that getCNumber is method, not a variable, so you need to call it - add a couple of braces after the method name, as I've shown above.
Also, it's generally a better idea to stick to python naming conventions and start the names of your variables from the lower-case letters - so you should rename the Dict variable to something like dict.
If you need to traverse the keys of your dictionary in the sorted order, you can write the for loop like so:

for key in sorted(dict.keys()):

Upvotes: 2

user2357112
user2357112

Reputation: 280446

for key in Map.keys():

You were calling your dict Dict before. If what you've posted is what you actually ran, then this is iterating over an entirely unrelated dict.

  print("Customer Number: " + c.getCNumber)

You refer to c here, rather than anything related to key. c is still the last customer you created. If Map contains two keys, this will print c's information twice. (Actually, since the function call parentheses are missing, it might print something along the lines of <bound method object at...>.)

Upvotes: 1

Related Questions