preamble
Dictionary is a must-have and commonly used data structure in Python, this article combs commonly used dictionary operations, see this is enough to involve:
- initialization
- Combining Dictionaries
- dictionary derivation
- Collections Standard Library
- Dictionary to JSON
- Dictionary to Pandas
initialization
# It's most commonly used my_object = { "a": 5, "b": 6 } # If you don't like writing curly braces and double quotes: my_object = dict(a=5, b=6)
Combining Dictionaries
a = { "a": 5, "b": 5 } b = { "c": 5, "d": 5 } c = { **a, **b } # The easiest way assert c == { "a": 5, "b": 5, "c": 5, "d": 5 } # And you have to modify it after the merger, so you can do that: c = { **a, **b, "a": 10 } assert c == { "a": 10, "b": 5, "c": 5, "d": 5 } b["a"] = 10 c = { **a, **b } assert c == { "a": 10, "b": 5, "c": 5, "d": 5 }
dictionary derivation
# Use dictionary derivatives to remove the key a = dict(a=5, b=6, c=7, d=8) remove = set(["c", "d"]) a = { k: v for k,v in () if k not in remove } # a = { "a": 5, "b": 6 } # Use dictionary derivatives to keep the key a = dict(a=5, b=6, c=7, d=8) keep = remove a = { k: v for k,v in () if k in keep } # a = { "c": 7, "d": 8 } # Use dictionary derivatives to make all values plus 1 a = dict(a=5, b=6, c=7, d=8) a = { k: v+1 for k,v in () } # a = { "a": 6, "b": 7, "c": 8, "d": 9 }
Collections Standard Library
Collections is a built-in module in Python that has several useful dictionary subclasses that can greatly simplify Python code. Two of the classes I use a lot are defaultdict and Counter, and because it's a subclass of dict, it has standard methods like items(), keys(), values(), and so on.
from collections import Counter counter = Counter() #counter counts the frequency of elements in a list. (['a','b','a'] # At this point counter = Counter({'a': 2, 'b': 1}) #Merge count ({ "a": 10000, "b": 1 }) # Counter({'a': 10002, 'b': 2}) counter["b"] += 100 # Counter({'a': 10002, 'b': 102}) print(counter.most_common()) #[('a', 10002), ('b', 102)] print(counter.most_common(1)[0][0]) # => a
defaultdict is also a must-have for dict:
from collections import defaultdict # If the value of the dictionary is the dictionary a = defaultdict(dict) assert a[5] == {} a[5]["a"] = 5 assert a[5] == { "a": 5 } # If the value of the dictionary is a list a = defaultdict(list) assert a[5] == [] a[5].append(3) assert a[5] == [3] # The default value of a dictionary's value can be a lambda expression a = defaultdict(lambda: 10) assert a[5] == 10 assert a[6] + 1 == 11 # Another dictionary inside a dictionary, how many initialization operations do you have to do without this? a = defaultdict(lambda: defaultdict(dict)) assert a[5][5] == {}
Dictionary to JSON
By JSON we usually mean a JSON string, which is a character string.Dict can be converted to a string in JSON format.
import json a = dict(a=5, b=6) # Dictionary to JSON String json_string = (a) # json_string = '{"a": 5, "b": 6}' # JSON string to dictionary assert a == (json_string) # Dictionary to JSON string saved in file with open("", "w+") as f: (a, f) # Recover dictionaries from JSON files with open("", "r") as f: assert a == (f)
Dictionary to Pandas
import pandas as pd # Dictionary to df = ([ { "a": 5, "b": 6 }, { "a": 6, "b": 7 } ]) # df = # a b # 0 5 6 # 1 6 7 # DataFrame back to dictionary a = df.to_dict(orient="records") # a = [ # { "a": 5, "b": 6 }, # { "a": 6, "b": 7 } # ] # Dictionary to srs = ({ "a": 5, "b": 6 }) # srs = # a 5 # b 6 # dtype: int64 # Back to the dictionary a = srs.to_dict() # a = {'a': 5, 'b': 6}
to this article on the Python dictionary in the common operations of the example of the article is introduced to this, more related Python dictionary content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!