-4
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

for items in dict:
    print items
    print value
Cœur
  • 37,241
  • 25
  • 195
  • 267
Avinash
  • 1
  • 1
  • 1
  • 1

3 Answers3

1

To iterate over both the key and the value of a dictionary, you can use the items() method, or for Python 2.x iteritems()

So the code you are looking for will be as followed:

d = {'Name' : 'Zara', 'Age' : '7', 'Class' : 'First'}
#dict is a key word, so you shouldn't write a variable to it

for key, value in d.items():
    print(key, value)

And if you were to use Python 2.x rather than 3.x, you would use this line in the for loop:

for key, value in d.iteritems():

I hope this has answered your question, just next time try to do a little more research, as there is probably another question answering this available.

George Willcox
  • 677
  • 12
  • 30
0

Try:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

for items in dict:
    print(items)
    print(dict[items])

Or if you want a format like, key:value, you can do: print(items,':', dict[items])

RPT
  • 728
  • 1
  • 10
  • 29
  • Basically, what you were trying to do was loop through every key in the dictionary (you did, `for items in dict:`). You then tried to print out `item` which was the key. Then you tried to do something like `print(value)`. But there exists nothing called `value`. What you can do instead is print the value of that key by using `dict[item]`. Read: https://docs.python.org/2/tutorial/datastructures.html#dictionaries – RPT May 01 '17 at 11:29
0

Easier:

dict.items()
dict.values()
Margarita Gonzalez
  • 1,127
  • 7
  • 20
  • 39