6 Python Dict Things I Wish I Knew Earlier
1) Using | to combine dicts
The | operator can be used to combine 2 dicts together
Note — if there exists duplicate keys, the later (rightmost) dictionaries take precedence
2) dict.get(key) VS dict[key]
We can use d.get(key) instead of d[key] to access the dictionary’s value without risk of raising a KeyError. When we use d.get(key):
if the key exists, the value is returned as per normal
if the key doesn’t exist,
Noneis returned by default (instead of raising aKeyErrorliked[key])
Note — we can use d.get(key, default_value) to specify a default value if we don’t want the default value to be None
3) .update()
We can use dict.update to add all key-value pairs in one dict to another.
Note — key-value pairs in d2 remain unchanged. Also, if there are duplicate keys, d2 takes precedence
4) Creating dicts with dict(key_value_pairs)
If we pass a list of key-value tuples into dict, we get a dict.
Applying this, we can do cool shortcuts/stuff like this:
5) .keys() .values() and .items()
.keys() produces the dict keys, .values() produces the dict values, while .items() produces key-value pairs. We often use these to iterate through our dictionaries.
Note — when we use for k in d: , technically we also iterate through the dict keys. But in production code, many of us explicitly write for k in d.keys() to make this immediately obvious.
6) Only immutable objects can be dict keys
In Python, objects are either mutable or immutable.
If an object is mutable, it can be changed (or mutated) after creation. Examples of mutable data types include list, dict, set etc
If an object is immutable, it cannot be changed (or mutated) after creation. Examples of immutable data types include int, float, bool, str, tuple etc
Only immutable data types can be dict keys.
Conclusion
Hopefully this was clear and easy to understand
If You Wish To Support Me As A Writer
Buy my Ebook — 256 Python Things I Wish I Knew Earlier at https://payhip.com/b/xpRco — a collection of hard-earned insights from writing 500,000+ lines of code over 9+years. Save yourself from years of trial and error
Thank you — these actions go a long way, and I really appreciate it.











