Python iterate dictionary

Iterate Python dictionary (associative arrays)

Using keys

It is not memory efficient for large dictionaries.

d = {"k1": "v1", "k2": "v2", "k3":"v3"}
for k in d:
  print(k)
## Or 
for k in d.keys():
  print(k)
k3
k2
k1
k3
k2
k1
Env: Python 2.7.6

Using values

It is not memory efficient for large dictionaries.

d = {"k1": "v1", "k2": "v2", "k3":"v3"}
for v in d.values():
  print(v)
v3
v2
v1
Env: Python 2.7.6

Using items (both keys and values)

It is not memory efficient for large dictionaries.

d = {"k1": "v1", "k2": "v2", "k3":"v3"}
for k, v in d.items():
  print(k, v)
('k3', 'v3')
('k2', 'v2')
('k1', 'v1')
Env: Python 2.7.6

Using iterkeys

It is more memory efficient for large dictionaries.

d = {"k1": "v1", "k2": "v2", "k3":"v3"}
for k in d.iterkeys():
  print(k)
k3
k2
k1
Env: Python 2.7.6

Using itervalues

It is more memory efficient for large dictionaries.

d = {"k1": "v1", "k2": "v2", "k3":"v3"}
for v in d.itervalues():
  print(v)
v3
v2
v1
Env: Python 2.7.6

Using iteritems

It is more memory efficient for large dictionaries.

d = {"k1": "v1", "k2": "v2", "k3":"v3"}
for k, v in d.iteritems():
  print(k, v)
('k3', 'v3')
('k2', 'v2')
('k1', 'v1')
Env: Python 2.7.6

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments