ZrSiO4
ZrSiO4

Reputation: 201

Iterate Over Dictionary

The two setups using print(i, j) and print(i) return the same result. Are there cases when one should be used over the other or is it correct to use them interchangeably?

desc = {'city': 'Monowi', 'state': 'Nebraska', 'county':'Boyd', 'pop': 1}

for i, j in desc.items():
 print(i, j)

for i in desc.items():
 print(i)

for i, j in desc.items():
 print(i, j)[1]

for i in desc.items():
 print(i)[1]

Upvotes: 8

Views: 37397

Answers (3)

A.B.
A.B.

Reputation: 169

In Python 3, print(i, j) and print(i) does not return the same result.

print(i, j) prints the key i followed by its value j.

print(i) prints a tuple containing the dictionary key followed by its value.

Upvotes: 1

Artier
Artier

Reputation: 1673

Both are different if remove parenthesis in print because you are using python 2X

desc = {'city': 'Monowi', 'state': 'Nebraska', 'county':'Boyd', 'pop': 1}

for i, j in desc.items():
 print i, j 

for i in desc.items():
 print i

output

county Boyd
city Monowi
state Nebraska
pop 1
('county', 'Boyd')
('city', 'Monowi')
('state', 'Nebraska')
('pop', 1)

Upvotes: 12

pjhades
pjhades

Reputation: 2038

items() returns a view object which allows you to iterate over the (key, value) tuples. So basically you can just manipulate them as what you do with tuples. The document may help:

iter(dictview) Return an iterator over the keys, values or items (represented as tuples > of (key, value)) in the dictionary.

Also I think print(i, j)[1] would result in error in Python 3 since print(i, j) returns None.

Upvotes: 0

Related Questions