<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"># 最常用这种
my_object = {
"a": 5,
"b": 6
}
# 如果你不喜欢写大括号和双引号:
my_object = dict(a=5, b=6)</pre><div class="contentsignin">Copy after login</div></div>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">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 }</pre><div class="contentsignin">Copy after login</div></div>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"># 使用字典推导式来删除 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 }</pre><div class="contentsignin">Copy after login</div></div>
Collections is a built-in module in Python that has several useful dictionary subclasses, 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.
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">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</pre><div class="contentsignin">Copy after login</div></div>
defaultdict is also the nirvana of dict:
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">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] == {}</pre><div class="contentsignin">Copy after login</div></div>
What we usually call JSON refers to JSON string, which is a string. Dict can be converted into a string in JSON format.
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">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)</pre><div class="contentsignin">Copy after login</div></div>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">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}</pre><div class="contentsignin">Copy after login</div></div>
The above is the detailed content of What are the basic operation methods of dictionary in Python?. For more information, please follow other related articles on the PHP Chinese website!