0x00: Create a one-click multi-value dictionary
Dictionary is a variable container in Python, which usually appears in this form:
d = {key1:value1, key2:value2, key3:value3}
Python does not specify the type of value in a dictionary, so if you want a key in a dictionary to correspond to multiple values, just put those values in a container such as a list.
student = { 'a': [76, 54, 82], 'b': [92, 67, 88] }
To facilitate the creation of such a dictionary, you can use the defaultdict class in the collections module. Generally, an error will be reported when accessing key s that do not exist in a dictionary, and the defaultdict class will automatically initialize a default value. Using defaultdict, you can create a dictionary with a list value as follows:
d = defaultdict(list) d['a'].append(1) d['a'].append(2) d['a'].append(3)
0x01: Ordered Dictionary
The key s of dictionaries in Python do not record the order. If we want to master the order of elements when iterating or serializing dictionaries, we can use the OrderedDict class in the collections module.
>>> from collections import OrderedDict >>> d = OrderedDict() >>> d['a'] = 1 >>> d['b'] = 2 >>> d['c'] = 3 >>> for key in d: ... print(key, d[key]) ... a 1 b 2 c 3
OrderedDict maintains a two-way list internally, and every time a new element is created in the dictionary, it is placed at the end of the list. Reassigning existing keys does not change the order of keys. Because OrderedDict creates additional linked lists, it takes up more space than a regular dictionary. Use this class to pay attention to trade-offs.
0x02: Deduplicate the sequence but keep the order unchanged
To remove duplicates from a list, you only need to use set(), which creates a set without duplicates and can perform intersection, union, and so on. However, this set of objects is out of order.
>>> a = [1, 4, 6, 1, 2, 1, 3, 6, 2] >>> b = set(a) >>> b {1, 2, 3, 4, 6}
If you want to remove duplicates and keep the order, you can solve it by adding a generator to set():
def dedupe(items): seen = set() for item in items: if item in items: if item not in seen: yield item seen.add(item)
This only works when elements in a sequence are immutable objects, such as integers, strings, tuples. If you want to apply to variable containers such as lists, you need to modify the code slightly:
def dedupe(items): seen = set() for item in items: val = item if key is None else key(item) if val not in seen: yield item seen.add(val)
The key parameter is used here to specify a function that converts elements in a sequence into immutable types.
0x03: Number of Statistical Elements
How to find the most frequent words in a book? Or would you like to know how many times the same element appears in a list? The Counter class in the collections module is easy to do.
>>> from collections import Counter >>> words = ['apple', 'keys', 'double', 'dude', 'eye', 'love', 'magic', 'double', 'magic', 'spell', 'apple', 'point', 'apple'] >>> count = Counter(words) >>> count Counter({'apple': 3, 'double': 2, 'magic': 2, 'keys': 1, 'dude': 1, 'eye': 1, 'love': 1, 'spell': 1, 'point': 1})
You can also use the most_common method of the Counter class to find the top elements:
>>> top = count.most_common(3) >>> print(top) [('apple', 3), ('double', 2), ('magic', 2)] >>>
In addition, Counter objects can also do mathematical operations:
>>> words = ['apple', 'keys', 'double', 'dude', 'eye', 'love', 'magic', 'double', 'magic', 'spell', 'apple', 'point', 'apple'] >>> other = ['apple', 'cool', 'duck', 'cookie'] >>> a = Counter(words) >>> b = Counter(other) >>> a Counter({'apple': 3, 'double': 2, 'magic': 2, 'keys': 1, 'dude': 1, 'eye': 1, 'love': 1, 'spell': 1, 'point': 1}) >>> b Counter({'apple': 1, 'cool': 1, 'duck': 1, 'cookie': 1}) >>> a + b Counter({'apple': 4, 'double': 2, 'magic': 2, 'keys': 1, 'dude': 1, 'eye': 1, 'love': 1, 'spell': 1, 'point': 1, 'cool': 1, 'duck': 1, 'cookie': 1}) >>>
Counter class can help us to do statistics well, of course, if you are doing algorithmic problems, please do not use it to clever.
0x04: Dictionary Derivation
To create a subset of a dictionary, you can easily use dictionary comprehension. Yes, lists have list generation and dictionaries have dictionary derivation.
>>> students = {'a':98, 'b':45, 'c':73, 'd':59} >>> passed = {key:value for key, value in students.items() if value >= 60} >>> passed {'a': 98, 'c': 73} >>>
Look, we can easily get the grades of the passing students through a dictionary that records all the students'grades.