


What are the basic operation methods of dictionary in Python?
Initialization
<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>
Merge dictionary
<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>
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(["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 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({ "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>
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 = '{"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>
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([
{ "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!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
