Initialization
<pre class="brush:php;toolbar:false"># 最常用这种
my_object = {
"a": 5,
"b": 6
}
# 如果你不喜欢写大括号和双引号:
my_object = dict(a=5, b=6)</pre>
Merge dictionary
<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>
Dictionary comprehension
<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>
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.
<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>
defaultdict is also the nirvana of dict:
<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>
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.
<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>
Dictionary to Pandas
<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>
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!

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

Python is suitable for rapid development and data processing, while C is suitable for high performance and underlying control. 1) Python is easy to use, with concise syntax, and is suitable for data science and web development. 2) C has high performance and accurate control, and is often used in gaming and system programming.

The time required to learn Python varies from person to person, mainly influenced by previous programming experience, learning motivation, learning resources and methods, and learning rhythm. Set realistic learning goals and learn best through practical projects.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function