Python Dict Examples

Last updated:
Table of Contents

WIP Alert This is a work in progress. Current information is correct but more content may be added in the future.

Filter dict by keys

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 dict 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 dict 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)]

Sort dict by value

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

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

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

References

Dialogue & Discussion