Want the unique key-value pairs from two Python dicts? dict.items() returns a set-like object: This returns the unique key-value pairs: {(‘b’, 20), (‘a’, 10), (‘d’, 40), (‘c’, 30)}
Want the unique keys from two Python dicts? dict.keys() returns a set-like object, supporting set operators:
Differences between dict.pop and dict.popitem in Python: dict.pop: – removes a pair based on a key– returns removed value– optional 2nd arg is returned if key isn’t there dict.popitem: – no arguments– returns the most-recently-inserted pair– returns (key, value) tuple
To remove a key-value pair from a Python dict, use dict.pop: Or… pass a second argument to dict.pop. You’ll get it instead of an exception:
Merge two Python dicts with | which returns a new dict. Conflicts? The right-side dict gets priority: d1 | d2 # {‘a’: 10, ‘b’: 100, ‘c’: 200, ‘d’: 300}d2 | d1 # {‘b’: 20, ‘c’: 30, ‘d’: 300, ‘a’: 10}
Iterating over a Python dict? Modifying existing values is fine, but adding or removing keys during iteration raises RuntimeError:
Want to iterate over a Python dict? The “items” method is your friend, returning a (key, value) tuple with each iteration: Remember: Insertion order determines iteration order.
Dictionaries in Python remember their insertion order, but equality ignores the ordering:
Want to create a dict of lists in Python? You can use defaultdict:
Want to create a dict of lists in Python? Use setdefault: