Dictionary is a necessary and commonly used data structure in Python. This article sorts out the commonly used dictionary operations. It is enough to look at this. It involves:
# 最常用这种 my_object = { "a": 5, "b": 6 } # 如果你不喜欢写大括号和双引号: my_object = dict(a=5, b=6)
a = { "a": 5, "b": 5 } b = { "c": 5, "d": 5 } c = { **a, **b } #最简单的方式 assert c == { "a": 5, "b": 5, "c": 5, "d": 5 } # 合并后还要修改,可以这样: 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 }
# 使用字典推导式来删除 key a = dict(a=5, b=6, c=7, d=8) remove = set(["c", "d"]) a = { k: v for k,v in a.items() if k not in remove } # a = { "a": 5, "b": 6 } # 使用字典推导式来保留 key a = dict(a=5, b=6, c=7, d=8) keep = remove a = { k: v for k,v in a.items() if k in keep } # a = { "c": 7, "d": 8 } # 使用字典推导式来让所有的 value 加 1 a = dict(a=5, b=6, c=7, d=8) a = { k: v+1 for k,v in a.items() } # a = { "a": 6, "b": 7, "c": 8, "d": 9 }
Collections is a built-in module in Python. It has several useful dictionary subclasses that can greatly simplify Python. code. Two of the classes I use frequently are defaultdict and Counter. Furthermore, since it is a subclass of dict, it has standard methods like items(), keys(), values(), etc.
from collections import Counter counter = Counter() #counter 可以统计 list 里面元素的频率 counter.update(['a','b','a'] #此时 counter = Counter({'a': 2, 'b': 1}) #合并计数 counter.update({ "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 the nirvana of dict:
from collections import defaultdict # 如果字典的 value 是 字典 a = defaultdict(dict) assert a[5] == {} a[5]["a"] = 5 assert a[5] == { "a": 5 } # 如果字典的 value 是列表 a = defaultdict(list) assert a[5] == [] a[5].append(3) assert a[5] == [3] # 字典的 value 的默认值可以是 lambda 表达式 a = defaultdict(lambda: 10) assert a[5] == 10 assert a[6] + 1 == 11 # 字典里面又是一个字典,不用这个,你要做多少初始化操作? a = defaultdict(lambda: defaultdict(dict)) assert a[5][5] == {}
What we usually call JSON refers to a JSON string, which is a string. Dict can be converted into a string in JSON format.
import json a = dict(a=5, b=6) # 字典转 JSON 字符串 json_string = json.dumps(a) # json_string = '{"a": 5, "b": 6}' # JSON 字符串转字典 assert a == json.loads(json_string) # 字典转 JSON 字符串保存在文件里 with open("dict.json", "w+") as f: json.dump(a, f) # 从 JSON 文件里恢复字典 with open("dict.json", "r") as f: assert a == json.load(f)
import pandas as pd # 字典转 pd.DataFrame df = pd.DataFrame([ { "a": 5, "b": 6 }, { "a": 6, "b": 7 } ]) # df = #ab # 056 # 167 # DataFrame 转回字典 a = df.to_dict(orient="records") # a = [ #{ "a": 5, "b": 6 }, #{ "a": 6, "b": 7 } # ] # 字典转 pd.Series srs = pd.Series({ "a": 5, "b": 6 }) # srs = # a5 # b6 # dtype: int64 # pd.Series 转回字典 a = srs.to_dict() # a = {'a': 5, 'b': 6}
The above is the detailed content of Regarding dictionary operations in Python, it is enough to read this. For more information, please follow other related articles on the PHP Chinese website!