8

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]
L3viathan
  • 26,748
  • 2
  • 58
  • 81
ZrSiO4
  • 201
  • 1
  • 2
  • 7
  • Possible duplicate of [Iterating over dictionaries using 'for' loops](https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops) – oshaiken Feb 02 '18 at 15:14
  • They're functionally equivalent, so use whichever makes your code more readable. – Aran-Fey Feb 02 '18 at 15:18
  • 1
    In Python 3, they are _not_ equivalent: The first prints the items seperated by a space, the second prints a tuple. – L3viathan Feb 02 '18 at 15:20
  • If you need to use the keys and values separately then use the first approach, this is the most common case for iterating over a `dict` – Chris_Rands Feb 02 '18 at 15:21

3 Answers3

12

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)
Artier
  • 1,648
  • 2
  • 8
  • 22
1

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.

Owen
  • 7,494
  • 10
  • 42
  • 52
A.B.
  • 169
  • 10
0

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.

pjhades
  • 1,948
  • 2
  • 19
  • 34