8 Python Dictionary Things I Regret Not Knowing Earlier
8 Python Dictionary Things I Regret Not Knowing Earlier
These tips have made dealing with dictionaries in Python a lot more enjoyable and
elegant, and I kinda wish I learnt them a little less late.
Note — this is the way that my dev team creates dictionaries 95% of the time. We
don’t use {} very much.
when we use {}, we need to type the quote characters on string keys
for instance, 'apple' 'orange' and so on
having to type quote characters becomes exponentially annoying as we
have to deal with more and more keys
when we use dict(), we can ignore the quote characters
Of course, the dict() way doesn’t work with non-string keys, so both ways have
their uses.
a = {1:1, 2:2}
b = {3:3, 4:4}
# we can combine them using **
x = {**a, **b}
the ** in front of the dictionaries unpacks the key-value pairs into the
parent dictionary
a = {1:1, 2:2}
b = {3:3, 4:4}
We can dynamically pass in a dictionary containing the keys a b and c into this
function too
test(**mydict) # 1 2 3
^ the ** in front of the dict once again unpacks its key-value pairs into the
function test
4) Dictionary comprehension
d = {}
for i in range(1, 5):
d[i] = i**2
d = {}
for i in range(2):
for j in range(2, 4):
d[(i,j)] = 0
print(d)
print(d)
5) dict.get(key, default_value)
print(d[1]) # 1
print(d[4]) # KeyError
If we really don’t want a KeyError, we can use the .get() method instead, which
returns None if our key is non-existent.
# using .get()
print(d.get(1)) # 1
print(d.get(4)) # None
print(d.get(1, 100)) # 1
print(d.get(4, 100)) # 100
print(d.get(9, 100)) # 100
d = dict(ls)
^ this has been surprisingly useful in quickly creating dictionaries from tuples
without having to write dictionary comprehensions.
# a dict
When we iterate through the dict itself, we simply generate all dict keys:
for k in d:
print(k)
# apple
# orange
# pear
for v in d.values():
print(v)
# 4
# 5
# 6
# apple 4
# orange 5
# pear 6
^ I myself find .items() the most useful method here to quickly iterate through all
key-value pairs in a dictionary.
In general:
immutable data types can be dict keys eg. int str tuple bool
mutable data types cannot eg. list dict
mylist = [1,2,3]
d = {mylist: 5}
To legitimately check if some object can be used as a dict key, we can use the built-
in hash() function.
a: int = 4
b: str = 'hi'
print(hash(a)) # 4
print(hash(b)) # -4763374371541057969
# using hash() on mutable data types
l: list = [1, 2, 3]
d: dict = {1:1}
So if you wish to create a custom object that can be a dictionary key, you can use
the __hash__ magic method to define how we want to hash our custom object.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def __hash__(self):
return hash(str(self.name) + str(self.age))
dog1 = Dog('rocky', 4)
dog2 = Dog('fifi', 5)
d = {dog1: 1, dog2: 2}
print(d)