Python Dict Examples

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

Iterate over values in a dict with .items():

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

for key,val in d.items():
    print(f"{key} => {val}")
# >>> foo => 10
# >>> bar => 30
# >>> baz => 20

Sort by key

To order dict elements by key, 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 by value

Similar to the above, to order dict elements by key, turn them into an ordered list of tuples:

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

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

Dict to OrderedDict

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

To create an OrderedDict from dict

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

See below for a better solution if you're running Python 3.5+

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

# 'b' is in both dicts, but the FORMER (value in d1) takes precedence
d3['b']
# >>> 2

d3['c']
# >>> 200

Merge dicts, Python 3.5+

Python 3.5+ only

d1 = {'a':1, 'b': 2}

d2 = {'b':100, 'c': 200}

d3 = {**d1, **d2}

d3['a']
# >>> 1

# 'b' is in both dicts, but the LATTER (value in d2) takes precedence
d3['b']
# >>> 100

d3['c']
# >>> 200

Add value to dict, Python 3.5+

It's just a slight variation of the above:

Example: add a new key 'c' with value 3 to the dict and return a copy (i.e. no in-place mutation)

d1 = {'a':1, 'b':2}

updated_d1 = {**d1, **{'c':3}}

updated_d1
# >>> {'a': 1, 'b': 2, 'c': 3}

# d1 wasn't changed
d1
# >>> {'a': 1, 'b': 2}

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}

Pretty print dict

Turn it into a JSON object with json library abd use json.dumps():

import json

d = {"foo": {"bar": "baz", "quux": {"qaax" :456}}, "xxx": 123, "yyy": [7,8,9,0]}

json.dumps(d,indent=2)
# >>>
#{
#  "foo": {
#    "bar": "baz",
#    "quux": {
#      "qaax": 456
#    }
#  },
#  "xxx": 123,
#  "yyy": [
#    7,
#    8,
#    9,
#    0
#  ]
#}