Literal syntax
d = {} d = {'key': 'value'} # makes a shallow copy of otherdict d = {**otherdict} # also updates the shallow copy with the contents of the yetanotherdict. d = {**otherdict, **yetanotherdict} # dict comprehension d = {k:v for k,v in [('key', 'value',)]}
Dict.get method
One common pitfall when using dictionaries is to access a non-existent key. This typically results in a KeyError exception. One way to avoid key errors is to use the dict.get method, which allows you to specify a default value to return in the case of an absent key.
value = mydict.get(key, default_value)
Which returns mydict[key] if it exists, but otherwise returns default_value . Note that this doesn’t add key to mydict . So if you want to retain that key value pair, you should use mydict.setdefault(key, default_value) , which does store the key value pair.
mydict = {} print(mydict) # {} print(mydict.get("foo", "bar")) # bar print(mydict) # {} print(mydict.setdefault("foo", "bar")) # bar print(mydict) # {'foo': 'bar'}
Merging dictionaries
# Consider the following dictionaries: fish = {'name': "Nemo", 'hands': "fins", 'special': "gills"} dog = {'name': "Clifford", 'hands': "paws", 'color': "red"} fishdog = {**fish, **dog} print(fishdog) # {'hands': 'paws', 'color': 'red', 'name': 'Clifford', 'special': 'gills'}
As this example demonstrates, duplicate keys map to their lattermost value (for example “Clifford” overrides “Nemo”).
Unpacking dictionaries using the ** operator
You can use the ** keyword argument unpacking operator to deliver the key -value pairs in a dictionary into a function’s arguments.
def parrot(voltage, state, action): print("This parrot wouldn't", action, end=' ') print("if you put", voltage, "volts through it.", end=' ') print("E's", state, "!") d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"} parrot(**d) # This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
Dictionary Comprehensions
A dictionary comprehension is similar to a list comprehension except that it produces a dictionary object instead of a list.
F=dict((x, x * x) for x in (1, 2, 3, 4)) print(F) # Out: {1: 1, 2: 4, 3: 9, 4: 16}
As with a list comprehension, we can use a conditional statement inside the dict comprehension to produce only the dict elements meeting some criterion.
F={name: len(name) for name in ('Fcuk', 'The', 'Code') if len(name) > 3} print(F) # Out: {'Fcuk': 4, 'Code': 4}
Starting with a dictionary and using dictionary comprehension as a key-value pair filter
initial_dict = {'F': 1, 'C': 2} F={key: value for key, value in initial_dict.items() if key == 'F'} print(F) # Out: {'F': 1}
Switching key and value of dictionary (invert dictionary)
If you have a dict containing simple hashable values (duplicate values may have unexpected results):
my_dict = {1: 'a', 2: 'b', 3: 'c'}
you wanted to swap the keys and values you can take several approaches depending on your coding style:
'''Approaches''' ''' #1 '''swapped = {v: k for k, v in my_dict.items()} ''' #2 '''swapped = dict((v, k) for k, v in my_dict.iteritems()) ''' #3 '''swapped = dict(zip(my_dict.values(), my_dict)) ''' #4 '''swapped = dict(zip(my_dict.values(), my_dict.keys())) ''' #5 '''swapped = dict(map(reversed, my_dict.items())) print(swapped) '''All leads to same output ''' # Output: {a: 1, b: 2, c: 3}
If your dictionary is large, consider importing itertools and utilize izip or imap .
Merging Dictionaries
Combine dictionaries and optionally override old values with a nested dictionary comprehension.
dict1 = {'w': 1, 'x': 1} dict2 = {'x': 2, 'y': 2, 'z': 2} F={k: v for d in [dict1, dict2] for k, v in d.items()} print(F) # Out: {'w': 1, 'x': 2, 'y': 2, 'z': 2} #Python 3.x Version F={**dict1, **dict2} print(F) # Out: {'w': 1, 'x': 2, 'y': 2, 'z': 2}