What are the basic operation methods of dictionary in Python?

PHPz
Release: 2023-04-21 17:43:20
forward
973 people have browsed it

Initialization

<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"># 最常用这种 my_object = { &quot;a&quot;: 5, &quot;b&quot;: 6 } # 如果你不喜欢写大括号和双引号: my_object = dict(a=5, b=6)</pre><div class="contentsignin">Copy after login</div></div>

Merge dictionary

<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">a = { &quot;a&quot;: 5, &quot;b&quot;: 5 } b = { &quot;c&quot;: 5, &quot;d&quot;: 5 } c = { **a, **b } #最简单的方式 assert c == { &quot;a&quot;: 5, &quot;b&quot;: 5, &quot;c&quot;: 5, &quot;d&quot;: 5 } # 合并后还要修改,可以这样: c = { **a, **b, &quot;a&quot;: 10 } assert c == { &quot;a&quot;: 10, &quot;b&quot;: 5, &quot;c&quot;: 5, &quot;d&quot;: 5 } b[&quot;a&quot;] = 10 c = { **a, **b } assert c == { &quot;a&quot;: 10, &quot;b&quot;: 5, &quot;c&quot;: 5, &quot;d&quot;: 5 }</pre><div class="contentsignin">Copy after login</div></div>

Dictionary comprehension

<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([&quot;c&quot;, &quot;d&quot;]) a = { k: v for k,v in a.items() if k not in remove } # a = { &quot;a&quot;: 5, &quot;b&quot;: 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 = { &quot;c&quot;: 7, &quot;d&quot;: 8 } # 使用字典推导式来让所有的 value 加 1 a = dict(a=5, b=6, c=7, d=8) a = { k: v+1 for k,v in a.items() } # a = { &quot;a&quot;: 6, &quot;b&quot;: 7, &quot;c&quot;: 8, &quot;d&quot;: 9 }</pre><div class="contentsignin">Copy after login</div></div>

Collections Standard Library

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({ &quot;a&quot;: 10000, &quot;b&quot;: 1 }) # Counter({'a': 10002, 'b': 2}) counter[&quot;b&quot;] += 100 # Counter({'a': 10002, 'b': 102}) print(counter.most_common()) #[('a', 10002), ('b', 102)] print(counter.most_common(1)[0][0]) # =&gt; 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][&quot;a&quot;] = 5 assert a[5] == { &quot;a&quot;: 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>

Dictionary to JSON

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 = '{&quot;a&quot;: 5, &quot;b&quot;: 6}' # JSON 字符串转字典 assert a == json.loads(json_string) # 字典转 JSON 字符串保存在文件里 with open(&quot;dict.json&quot;, &quot;w+&quot;) as f: json.dump(a, f) # 从 JSON 文件里恢复字典 with open(&quot;dict.json&quot;, &quot;r&quot;) as f: assert a == json.load(f)</pre><div class="contentsignin">Copy after login</div></div>

Dictionary to Pandas

<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([ { &quot;a&quot;: 5, &quot;b&quot;: 6 }, { &quot;a&quot;: 6, &quot;b&quot;: 7 } ]) # df = #ab # 056 # 167 # DataFrame 转回字典 a = df.to_dict(orient=&quot;records&quot;) # a = [ #{ &quot;a&quot;: 5, &quot;b&quot;: 6 }, #{ &quot;a&quot;: 6, &quot;b&quot;: 7 } # ] # 字典转 pd.Series srs = pd.Series({ &quot;a&quot;: 5, &quot;b&quot;: 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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template