Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 558
ZrSiO4 Avatar asked Feb 02 '18 15:02

ZrSiO4


People also ask

Can you iterate over a dictionary?

You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.

Can you iterate over a dictionary in Python?

You can iterate through a Python dictionary using the keys(), items(), and values() methods. keys() returns an iterable list of dictionary keys. items() returns the key-value pairs in a dictionary. values() returns the dictionary values.

Can you iterate over dictionary keys?

There are literally no restrictions for values. In Python 3.6 and beyond, the keys and values of a dictionary are iterated over in the same order in which they were created.


1 Answers

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)
like image 78
Artier Avatar answered Sep 22 '22 15:09

Artier