Dictionary (dict) object is Python's most commonly used data structure, the community has been joked that "Python attempts to load the entire world with dictionaries", the importance of dictionaries in Python is self-evident, here compiled a list of several on the efficient use of dictionaries, hope that Python developers can be reasonable use of the day-to-day development of the application, so that the code is more Pythonic.
1. Use the in keyword to check if the key exists.
One of the development philosophies in Zen of Python is:
There should be one-- and preferably only one --obvious way to do it.
Try to find a solution, preferably the only obvious one; in Python2, you can determine whether a key exists in a dictionary using the has_key method, or you can use the in keyword. The latter is highly recommended, however, because in is faster, and because the has_key method was removed in Python3, making in the best choice for compatibility with both Python2 and Python3.
bad d = {'name': 'python'} if d.has_key('name'): pass good if 'name' in d: pass
2, use get to get the value of the dictionary
Regarding getting the value in the dictionary, a simple way is to access the element with d[x], but this will report a KeyError error if the key doesn't exist. Of course, you can use the in operation to check if the key is in the dictionary before you get it, but this way doesn't conform to what is said in Zen of Python:
Simple is better than complex.
Flat is better than nested.
Good code should be simple to understand, and flat code structures are more readable. Instead of the if ... method, we can use the get method. else
bad d = {'name': 'python'} if 'name' in d: print(d['hello']) else: print('default') good print(("name", "default"))
3. Use setdefault to set a default value for a key that does not exist in the dictionary.
data = [ ("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus") ]
When doing categorical statistics, you want to group the same type of data into a certain type in a dictionary, such as the code above, which reassembles things of the same type in the form of a list to get a new dictionary
groups = {} >>> {'plant': ['cactus'], 'animal': ['bear', 'duck'], 'vehicle': ['speed boat', 'school bus']}
The normal way is to determine whether the key already exists, and if not, to initialize it with a list object before performing the subsequent operations. A better way is to use the setdefault method in the dictionary.
bad for (key, value) in data: if key in groups: groups[key].append(value) else: groups[key] = [value] good groups = {} for (key, value) in data: (key, []).append(value)
What setdefault does:
If the key exists in the dictionary, then the corresponding value is returned, which is equivalent to the get method.
If the key does not exist in the dictionary, the second argument to setdefault is used as the value of the key and the value is returned.
4. Initialize the dictionary object with defaultdict.
If you don't want d[x] to error out when x doesn't exist, another way to do it, besides using the get method when fetching the element, is to use defaultdict from the collections module, which specifies a function when initializing the dictionary; in fact, defaultdict is a subclass of dict.
from collections import defaultdict groups = defaultdict(list) for (key, value) in data: groups[key].append(value)
When the key doesn't exist in the dictionary, the list function is called and returns an empty list to assign to d[key], so you don't have to worry about calling d[k] with an error.
5. Use fromkeys to convert a list into a dictionary.
keys = {'a', 'e', 'i', 'o', 'u' } value = [] d = (keys, value) print(d) >>> {'i': [], 'u': [], 'e': [], 'a': [], 'o': []}
6、Using the dictionary to realize switch ... case statement
Python does not have a switch ... case statement in Python, and Uncle Turtle, the father of Python, said that this syntax was not, is not, and will never be. The reason is that Python's clean syntax can be realized with if ... elif statements. elif. If there are too many branching judgments, you can use a dictionary instead.
if arg == 0: return 'zero' elif arg == 1: return 'one' elif arg == 2: return "two" else: return "nothing" good data = { 0: "zero", 1: "one", 2: "two", } (arg, "nothing")
7. Use iteritems to iterate over the elements in the dictionary.
python provides several ways to iterate through the elements of a dictionary, the first being using the items method:
d = { 0: "zero", 1: "one", 2: "two", } for k, v in (): print(k, v)
items method returns a list object consisting of (key ,value), the disadvantage of this approach is that when iterating over a very large dictionary, the memory will instantly expand twice as much, because the list object will load all the elements into memory at once, a better way is to use iteritems
for k, v in (): print(k, v)
iteritems returns an iterator object, which is loaded inertly, generating values only when they're really needed, in a way that doesn't require additional memory to load the data during iteration. Note that in Python3, there is only the items method, which is equivalent to iteritems in Python2, and the method name iteritems has been removed.
8, the use of dictionary derivatives
Derivatives are a wonderful thing, and list derivatives overshadow functions such as map and filter. Since Python 2.7 and later, this feature has been extended to dictionaries and collections, which can be constructed without calling the dict method.
bad numbers = [1,2,3] d = dict([(number,number*2) for number in numbers]) good numbers = [1, 2, 3] d = {number: number * 2 for number in numbers}
summarize
The above is a list of efficient use of Python dictionaries, I hope it will help you, if you have any questions please leave me a message, I will reply to you in time. I would also like to thank you very much for your support of my website!