Dev Notes

Software Development Resources by David Egan.

Iterating Over Dictionary in Python


Data Structures, Python
David Egan

A dictionary in Python is a collection of unordered values accessed by key rather than index. Dictionary elements have no intrinsic order.

This short article shows several methods for iterating over Python dictionaries.

The examples in this article are Python 3.

Example dictionary:

transaction = {
  "amount": 10.00,
  "payee": "Joe Bloggs",
  "account": 1234
}

Iterate via keys

for key in transaction:
    print("{}: {}".format(key, transaction[key]))

# Output:
account: 1234
payee: Joe Bloggs
amount: 10.0

Iterate values only

for value in transaction.values():
    print(value)

# Output:
1234
Joe Bloggs
10.0

Iterate over key value pairs

for key, value in transaction.items():
    print("{}: {}".format(key, value))

# Output:
account: 1234
payee: Joe Bloggs
amount: 10.0

I often confuse this with the PHP foreach construct - forgetting to chain the items() method to the dictionary being iterated over.

Iterate over keys in the sorted order of the keys

for key in sorted(transaction):
    print("{}: {}".format(key, transaction[key]))

# Output:
account: 1234
amount: 10.0
payee: Joe Bloggs

Reference


comments powered by Disqus