10 Awesome Python Dictionary Tricks
Python dictionaries are one of the most useful data structures in Python. They are used to store key-value pairs. Dictionaries are mutable, which means that they can be changed after they are created. Dictionaries are unordered, which means that the order in which you add items to a dictionary does not matter. Dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.
1. Using defaultdict
Defaultdict saves you from checking if a key exists in a dictionary before accessing it. It is a subclass of the built-in dict class. Basically, it is a dictionary where the values have a default value if that key has not been set yet. The default value is defined in the constructor.
from collections import defaultdict
d = defaultdict(0)
d['a'] += 1 # This will not throw an error
2. Using get() with a default value
The get()
method returns the value for the given key. If key is not available then returns default value None.
This method takes 2 parameters, key and default value. If the key is not found, then the default value is returned.
d = {'a': 1, 'b': 2}
print(d.get('a')) # 1
print(d.get('c')) # None
print(d.get('c', 3)) # 3
3. Merging dictionaries
A common task is to merge two dictionaries. This can be done in a few different ways. The simplest way is to use the update()
method.
d1 = {'a': 1, 'b': 2}
d2 = {'b': 3, 'c': 4}
d1.update(d2)
print(d1) # {'a': 1, 'b': 3, 'c': 4}
Another way is to use the |
operator.
d1 = {'a': 1, 'b': 2}
d2 = {'b': 3, 'c': 4}
d3 = d1 | d2
print(d3) # {'a': 1, 'b': 3, 'c': 4}
4. Create a dictionary from two lists
You can create a dictionary from two lists using the zip()
function.
keys = ['a', 'b', 'c']
values = [1, 2, 3]
d = dict(zip(keys, values))
print(d) # {'a': 1, 'b': 2, 'c': 3}
5. Create a dictionary from a list of tuples
You can even create a dictionary from a list of tuples using the dict()
function.
l = [('a', 1), ('b', 2), ('c', 3)]
d = dict(l)
print(d) # {'a': 1, 'b': 2, 'c': 3}
6. Create a dictionary from keyword arguments
You can create a dictionary from keyword arguments using the dict()
function.
d = dict(a=1, b=2, c=3)
print(d) # {'a': 1, 'b': 2, 'c': 3}
7. Create a dictionary from a string
You can create a dictionary from a string using the dict()
function.
s = 'abc'
d = dict.fromkeys(s)
print(d) # {'a': None, 'b': None, 'c': None}
8. Spread operator
The spread operator **
can be used to unpack a dictionary into keyword arguments.
def my_func(a, b, c):
print(a, b, c)
d = {'a': 1, 'b': 2, 'c': 3}
my_func(**d) # 1 2 3
9. Dictionary comprehension using if
Dictionary comprehension can be used to create a new dictionary from an existing dictionary. You can also use an if
statement to filter out items. This trick is useful when you want to create a new dictionary from an existing dictionary, but only want to include certain items. Like filter in JavaScript.
d = {'a': 1, 'b': 2, 'c': 3}
d2 = {k: v for k, v in d.items() if v > 1}
print(d2) # {'b': 2, 'c': 3}
10. Using Counter
Counter is a Python class that is part of the collections module. It is used to count the number of occurrences of items in a list, tuple, or other iterable.
from collections import Counter
l = ['a', 'b', 'c', 'b', 'b', 'a']
c = Counter(l)
print(c) # Counter({'b': 3, 'a': 2, 'c': 1})
Bonus Tip
Do you know that everything in Python is an object? Even functions and classes are objects. This means you can generate functions dynamically.
def my_func(a, b):
return a + b
def my_func2(a, b):
return a * b
funcs = {'add': my_func, 'multiply': my_func2}
print(funcs['add'](1, 2)) # 3
print(funcs['multiply'](1, 2)) # 2