Python Dict Examples

Last updated:
Table of Contents

All examples assume Python version 3+

Filter by key

Return the items as a list of tuples then build a new dict.

allowed_keys = ['bar','baz']

d = {'foo':1,'bar':2}

filtered_items = [(k,v) for (k,v) in d.items() if k in allowed_keys]

dict(filtered_items)
# >> {'bar': 2}

Filter by value

allowed_values = [1, 2]

d = {'foo':1, 'bar':2, 'baz':3, 'quux':4 }

filtered_items = [(k,v) for (k,v) in d.items() if v in allowed_values]

dict(filtered_items)
# >> {'bar': 2, 'foo': 1}

For key, value in dict

d = {'foo':10,'bar':30,'baz':20}

for key,val in d.items():
    print('{} => {}'.format(key,val))

Sort by key

Dicts aren't sorted in Python but you can turn them into an ordered list of tuples:

d = {'foo':10,'bar':30,'baz':20}

sorted(d.items(),key=lambda x:x[0])
# >>> [('foo', 10), ('baz', 20), ('bar', 30)]

Order by key

See above: Sort by key

Sort by value

d = {'foo':10,'bar':30,'baz':20}

sorted(d.items(),key=lambda x:x[1])
# >>> [('bar', 30), ('baz', 20), ('foo', 10)]

Order by value

See above: Sort by value

Create OrderedDict from dict

An OrderedDict can be built from a sorted dict and you can trust items will be traversed in order:

from collections import OrderedDict

d = {'foo':10,'bar':30,'baz':20}

sorted_list_of_tuples = sorted(d.items(),key=lambda x:x[1])

od = OrderedDict(sorted_list_of_tuples)

# note that the items are traversed in order
for key,val in d.items():
    print('{} => {}'.format(key,val))

# >>> foo => 10
# >>> baz => 20
# >>> bar => 30

Create OrderedDict item by item

An OrderedDict remembers the order items were added:

from collections import OrderedDict

od = OrderedDict()

od['foo'] = 10
od['bar'] = 32
od['baz'] = 5

for key,val in od.items():
    print('{} => {}'.format(key,val))

# >>> foo => 10
# >>> bar => 32
# >>> baz => 5

Merge dicts

You can pass more than two dicts as arguments to ChainMap

Use ChainMap: ChainMap({}, d1, d2) (elements of d1 take prececence over elements of d2 in case of duplicates)

EXAMPLE: Merge two dicts:

from collections import ChainMap

d1 = {'a':1, 'b': 2}
d2 = {'b':100, 'c': 200}

d3 = ChainMap({}, d1, d2)

d3['a']
>>> 1

d3['b']
>>> 2

d3['c']
>>> 200

Dict comprehension

Use dict([(k,v) for k,v in mydict.items()])

Dict Comprehension: map keys

Example: Convert all dict keys to uppercase

mydict = {
    "a":1,
    "b":2
}
# >>> {'a': 1, 'b': 2}

dict([(k.upper(),v) for k,v in mydict.items()])
# >>> {'A': 1, 'B': 2}

Dict Comprehension: map values

Example: Multiply all values by two

mydict = {
    "a":1,
    "b":2
}
# >>> {'a': 1, 'b': 2}

dict([(k,v*2) for k,v in d1.items()])
# >>> {'a': 2, 'b': 4}


References

Dialogue & Discussion