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:
Want to assign to a Python dict, but only if the key doesn’t yet exist? Use setdefault:
Retrieve a value from a Python dict with the key: Request a key that doesn’t exist: Avoid that with dict.get, what I call “forgiving []”
Want to check if a Python dict contains a key? Use “in” on the dict: ‘a’ in d # True‘x’ in d # False Searching in d.keys() is far slower: ‘a’ in d # 10 ns‘a’ in d.keys() # 29 ns (!)
Want to create a Python dict? You have options; which is fastest? – Literal, with {‘a’:10, ‘b’:20}: 37.8 ns– Invoke dict(a=10, b=20): 58.5 ns– Invoke dict on a list of tuples, dict([(‘a’, 10), (‘b’, 20)]): 103 ns– Comprehension, {c : ord(c) for c in ‘ab’}: 78 ns
Trying to use .loc to retrieve a slice in Python Pandas? If the index repeats, you need to sort it: