7 Things I Never Knew About Dictionaries in Python Until Recently
# we can combine dictionaries using **

Day 45 of experimenting with video content
Summary
The provided content discusses seven lesser-known features of Python dictionaries, including combining dictionaries using **, using .get() for safe key access, updating dictionaries with .update(), understanding mapping proxies, iterating with .keys(), .values(), and .items(), typing dictionaries more efficiently, and creating dictionaries from iterables with dict.fromkeys.
Abstract
The article "7 Things I Never Knew About Dictionaries in Python Until Recently" delves into advanced and practical aspects of Python dictionaries that may not be common knowledge among all Python users. It begins by illustrating how to merge multiple dictionaries into one using the unpacking operator **, which simplifies the combination of key-value pairs. The author then highlights the utility of the .get() method to safely retrieve values without raising a KeyError. The .update() method is also discussed as a means to add key-value pairs from one dictionary to another. The concept of mapping proxies is introduced to explain the immutability of class dictionaries, which prevents accidental changes to class attributes. The article proceeds to explain the different methods for iterating over dictionaries, namely .keys(), .values(), and .items(), to access the desired elements. A more efficient syntax for defining dictionaries is presented, which is particularly useful when dealing with string keys. Lastly, the dict.fromkeys() method is demonstrated as a quick way to create a dictionary from an iterable, with the option to set a default value for all keys. The author concludes by expressing hope that readers have gained new insights into Python dictionaries.
Opinions
** to combine dictionaries is presented as a convenient and efficient method for merging dictionaries..get() method is implied to be a best practice for accessing dictionary values to avoid runtime errors..update() method is portrayed as a practical tool for batch insertion of key-value pairs into a dictionary.dict() and dict.fromkeys() can improve the readability and convenience of dictionary creation.
Day 45 of experimenting with video content
d1 = {'a':1, 'b':2}
d2 = {'c':3, 'd':4}
d3 = {**d1, **d2}
# {'a':1, 'b':2, 'c':3, 'd':4}When we use a ** in front of a dictionary, we are unpacking all key-value pairs into another dictionary. And we can use this to easily combine 2 or more dictionaries.
d1 = {'a':1, 'b':2}
d2 = {'c':3, 'd':4}
d3 = {'e':4, 'f':6}
d4 = {**d1, **d2, **d3}
# {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6}Note that we can use this syntax to combine 3 or more dictionaries too.
d = {'apple':4, 'orange':5}
print(d['apple']) # 4
print(d['pineapple']) # KeyErrorWhen we try to index a key that does not exist inside a dictionary, we usually get a KeyError (which may crash our program)
d = {'apple':4, 'orange':5}
print(d.get('apple')) # 4
print(d.get('pineapple')) # NoneWhen we use .get() instead of indexing, and we try to get a key that does not exist inside the dictionary, we get None instead of a KeyError
d = {'apple':4, 'orange':5}
print(d.get('apple', 100)) # 4
print(d.get('pineapple', 100)) # 100We can pass in a second argument into .get() — this second argument would be the default value that will be returned if we try to get a key that does not exist inside the dictionary.
d1 = {'a':1, 'b':2}
d2 = {'c':3, 'd':4}
d1.update(d2)
print(d1)
# {'a':1, 'b':2, 'c':3, 'd':4}Here, we use .update() to add every key-value pair in d2 into d1. So d1 will now contain every key-value pair that was in d2. This can be convenient if we want to quickly add multiple key-value pairs into our dictionary at one go.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print('woof')^ here we have a random Dog class.
dog = Dog('rocky', 4)
print(dog.__dict__) # {'name': 'rocky', 'age': 4}
print(type(dog.__dict__)) # <class 'dict'>The .__dict__ attribute of an object (a Dog object) is a normal dictionary, and contains the methods/attributes of the object.
print(Dog.__dict__)
# {'__module__': '__main__', '__init__': <function Dog.__init__ at 0x10c400cc0>,
# 'bark': <function Dog.bark at 0x10c401260>,
# '__dict__': <attribute '__dict__' of 'Dog' objects>, ...
# }
print(type(Dog.__dict__)) # <class 'mappingproxy'>Conversely, the .__dict__ attribute of a CLASS (not object) is a mapping proxy — which is simply an immutable dictionary (think a read-only dictionary)
This is so that we cannot randomly mutate the methods/attributes of a class in our code.
d = {'apple':4, 'orange':5, 'pear':6}
for key in d.keys():
print(key)
# apple
# orange
# pear^ to iterate through the keys, we use .keys()
d = {'apple':4, 'orange':5, 'pear':6}
for value in d.values():
print(value)
# 4
# 5
# 6^ to iterate through the values, we use .values()
d = {'apple':4, 'orange':5, 'pear':6}
for key, value in d.items():
print(key, value)
# apple 4
# orange 5
# pear 6^ to generate both key and value at the same time (key-value pair), we can use .items()
d = {'apple':4, 'orange':5, 'pear':6, 'pineapple':7, 'durian':8}^ how we usually create dictionaries
d = dict(apple=4, orange=5, pear=6, pineapple=7, durain=8)^ an alternative way to typing out a dictionary
Using this alternative way, we need not type as many quote characters ' for our string keys. This can be useful if we intend for our dictionary keys to be strings.
Note — this does not necessarily make our code execution faster. Just a more convenient way to type out a dictionary.
fruits = ['apple', 'orange', 'pear']
d = dict.fromkeys(fruits)
# {'apple':None, 'orange':None, 'pear':None}We can use dict.fromkeys to quickly generate a dictionary from a list (or some iterable). Note that all values in this dictionary would be the default value None
fruits = ['apple', 'orange', 'pear']
d = dict.fromkeys(fruits, 5)
# {'apple':5, 'orange':5, 'pear':5}If we pass in a second argument, this second argument would be the default value of the dictionary.
Hope you’ve learnt at least one new thing about Python dictionaries today
If this story was helpful and you wish to show a little support, you could:
These actions really really help me out, and are much appreciated!
Ebooks I’ve Written: https://zlliu.co/ebooks
LinkedIn: https://www.linkedin.com/in/zlliu/
Fares SayahMaximize Your Pandas Skills: Essential Tips and Tricks for Mastering Data Manipulation
Abhay ParasharScripts That Increased My Productivity and Performance
Meng LiApp Store Rejection: The Hidden String Costing Python Developers