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]
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With