Home Backend Development Python Tutorial Basics | Detailed explanations of 11 Python dictionary usages

Basics | Detailed explanations of 11 Python dictionary usages

Aug 08, 2023 pm 05:03 PM
python

This issue brings you a comprehensive analysis of the 11 methods of Python dictionary, I hope it will be helpful to you You helped.

Dictionary (Dictionary) is a commonly used data structure provided by Python. It is used to store data with mapping relationships, consisting of key (key) and value (value) It is composed of in pairs, the key and value are separated by colon:, and the items are separated by commas. The entire dictionary is enclosed by curly brackets {}, and the format is as follows:
dic = {key1 : value1, key2 : value2 }
Copy after login

Dictionaries are also called associative arrays or hash tables. Here are several common ways to create dictionaries:

# 方法1
dic1 = { 'Author' : 'Python当打之年' , 'age' : 99 , 'sex' : '男' }

# 方法2
lst = [('Author', 'Python当打之年'), ('age', 99), ('sex', '男')]
dic2 = dict(lst)

# 方法3
dic3 = dict( Author = 'Python当打之年', age = 99, sex = '男')

# 方法4
list1 = ['Author', 'age', 'sex']
list2 = ['Python当打之年', 99, '男']
dic4 = dict(zip(list1, list2))
Copy after login
字典创建的方式还有很多种,这里不再赘述。
字典由 dict 类代表,可以使用 dir(dict) 来查看该类包含哪些方法,输入命令,可以看到如下输出结果:
print('methods = ',methods)

methods = ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
Copy after login
字典的方法和属性有很多种,这里我们重点介绍以下11种方法:
['clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
Copy after login

1. dict.clear()

clear() 用于清空字典中所有元素(键-值对),对一个字典执行 clear() 方法之后,该字典就会变成一个空字典:
list1 = ['Author', 'age', 'sex']
list2 = ['Python当打之年', 99, '男']
dic1 = dict(zip(list1, list2))
# dic1 = {'Author': 'Python当打之年', 'age': 99, 'sex': '男'}

dic1.clear()
# dic1 = {}
Copy after login


2. dict.copy()

copy() 用于返回一个字典的浅拷贝:
list1 = ['Author', 'age', 'sex']
list2 = ['Python当打之年', 99, '男']
dic1 = dict(zip(list1, list2))

dic2 = dic1 # 浅拷贝: 引用对象
dic3 = dic1.copy() # 浅拷贝:深拷贝父对象(一级目录),子对象(二级目录)不拷贝,还是引用
dic1['age'] = 18

# dic1 = {'Author': 'Python当打之年', 'age': 18, 'sex': '男'}
# dic2 = {'Author': 'Python当打之年', 'age': 18, 'sex': '男'}
# dic3 = {'Author': 'Python当打之年', 'age': 99, 'sex': '男'}
Copy after login
其中 dic2 是 dic1 的引用,所以输出结果是一致的,dic3 父对象进行了深拷贝,不会随dic1 修改而修改,子对象是浅拷贝所以随 dic1 的修改而修改,注意父子关系。
拓展深拷贝:copy.deepcopy()
import copy

list1 = ['Author', 'age', 'sex']
list2 = ['Python当打之年', [18,99], '男']
dic1 = dict(zip(list1, list2))

dic2 = dic1
dic3 = dic1.copy()
dic4 = copy.deepcopy(dic1)
dic1['age'].remove(18)
dic1['age'] = 20

# dic1 = {'Author': 'Python当打之年', 'age': 20, 'sex': '男'}
# dic2 = {'Author': 'Python当打之年', 'age': 20, 'sex': '男'}
# dic3 = {'Author': 'Python当打之年', 'age': [99], 'sex': '男'}
# dic4 = {'Author': 'Python当打之年', 'age': [18, 99], 'sex': '男'}
Copy after login
dic2 是 dic1 的引用,所以输出结果是一致的;dic3 父对象进行了深拷贝,不会随dic1 修改而修改,子对象是浅拷贝所以随 dic1 的修改而修改;dic4 进行了深拷贝,递归拷贝所有数据,相当于完全在另外内存中新建原字典,所以修改dic1不会影响dic4的数据

3. dict.fromkeys()

fromkeys() 使用给定的多个键创建一个新字典,值默认都是 None,也可以传入一个参数作为默认的值:
list1 = ['Author', 'age', 'sex']
dic1 = dict.fromkeys(list1)
dic2 = dict.fromkeys(list1, 'Python当打之年')

# dic1 = {'Author': None, 'age': None, 'sex': None}
# dic2 = {'Author': 'Python当打之年', 'age': 'Python当打之年', 'sex': 'Python当打之年'}
Copy after login

4. dict.get()

get() 用于返回指定键的值,也就是根据键来获取值,在键不存在的情况下,返回 None,也可以指定返回值:
list1 = ['Author', 'age', 'sex']
list2 = ['Python当打之年', [18,99], '男']
dic1 = dict(zip(list1, list2))

Author = dic1.get('Author')
# Author = Python当打之年
phone = dic1.get('phone')
# phone = None
phone = dic1.get('phone','12345678')
# phone = 12345678
Copy after login


5. dict.items()

items() 获取字典中的所有键-值对,一般情况下可以将结果转化为列表再进行后续处理:
list1 = ['Author', 'age', 'sex']
list2 = ['Python当打之年', [18,99], '男']
dic1 = dict(zip(list1, list2))
items = dic1.items()
print('items = ', items)
print(type(items))
print('items = ', list(items))

# items = dict_items([('Author', 'Python当打之年'), ('age', [18, 99]), ('sex', '男')])
# <class &#39;dict_items&#39;>
# items = [(&#39;Author&#39;, &#39;Python当打之年&#39;), (&#39;age&#39;, [18, 99]), (&#39;sex&#39;, &#39;男&#39;)]
Copy after login


6. dict.keys()

keys() 返回一个字典所有的键:
list1 = [&#39;Author&#39;, &#39;age&#39;, &#39;sex&#39;]
list2 = [&#39;Python当打之年&#39;, [18,99], &#39;男&#39;]
dic1 = dict(zip(list1, list2))
keys = dic1.keys()
print(&#39;keys = &#39;, keys)
print(type(keys))
print(&#39;keys = &#39;, list(keys))

# keys = dict_keys([&#39;Author&#39;, &#39;age&#39;, &#39;sex&#39;])
# <class &#39;dict_keys&#39;>
# keys = [&#39;Author&#39;, &#39;age&#39;, &#39;sex&#39;]
Copy after login


7. dict.pop()

pop() 返回指定键对应的值,并在原字典中删除这个键-值对:
list1 = [&#39;Author&#39;, &#39;age&#39;, &#39;sex&#39;]
list2 = [&#39;Python当打之年&#39;, [18,99], &#39;男&#39;]
dic1 = dict(zip(list1, list2))
sex = dic1.pop(&#39;sex&#39;)
print(&#39;sex = &#39;, sex)
print(&#39;dic1 = &#39;,dic1)

# sex = 男
# dic1 = {&#39;Author&#39;: &#39;Python当打之年&#39;, &#39;age&#39;: [18, 99]}
Copy after login


8. dict.popitem()

popitem() 删除字典中的最后一对键和值:
list1 = [&#39;Author&#39;, &#39;age&#39;, &#39;sex&#39;]
list2 = [&#39;Python当打之年&#39;, [18,99], &#39;男&#39;]
dic1 = dict(zip(list1, list2))
dic1.popitem()
print(&#39;dic1 = &#39;,dic1)

# dic1 = {&#39;Author&#39;: &#39;Python当打之年&#39;, &#39;age&#39;: [18, 99]}
Copy after login


9. dict.setdefault()

setdefault() 和 get() 类似, 但如果键不存在于字典中,将会添加键并将值设为default:
list1 = [&#39;Author&#39;, &#39;age&#39;, &#39;sex&#39;]
list2 = [&#39;Python当打之年&#39;, [18,99], &#39;男&#39;]
dic1 = dict(zip(list1, list2))
dic1.setdefault(&#39;Author&#39;, &#39;当打之年&#39;)
print(&#39;dic1 = &#39;,dic1)
# dic1 = {&#39;Author&#39;: &#39;Python当打之年&#39;, &#39;age&#39;: [18, 99], &#39;sex&#39;: &#39;男&#39;}
dic1.setdefault(&#39;name&#39;, &#39;当打之年&#39;)
print(&#39;dic1 = &#39;,dic1)
# dic1 = {&#39;Author&#39;: &#39;Python当打之年&#39;, &#39;age&#39;: [18, 99], &#39;sex&#39;: &#39;男&#39;, &#39;name&#39;: &#39;当打之年&#39;}
Copy after login


10. dict.update(dict1)

update() 字典更新,将字典dict1的键-值对更新到dict里,如果被更新的字典中己包含对应的键-值对,那么原键-值对会被覆盖,如果被更新的字典中不包含对应的键-值对,则添加该键-值对
list1 = [&#39;Author&#39;, &#39;age&#39;, &#39;sex&#39;]
list2 = [&#39;Python当打之年&#39;, [18,99], &#39;男&#39;]
dic1 = dict(zip(list1, list2))
print(&#39;dic1 = &#39;,dic1)
# dic1 = {&#39;Author&#39;: &#39;Python当打之年&#39;, &#39;age&#39;: [18, 99], &#39;sex&#39;: &#39;男&#39;}

list3 = [&#39;Author&#39;, &#39;phone&#39; ]
list4 = [&#39;当打之年&#39;, 12345678]
dic2 = dict(zip(list3, list4))
print(&#39;dic2 = &#39;,dic2)
# dic2 = {&#39;Author&#39;: &#39;当打之年&#39;, &#39;phone&#39;: 12345678}

dic1.update(dic2)
print(&#39;dic1 = &#39;,dic1)
# dic1 = {&#39;Author&#39;: &#39;当打之年&#39;, &#39;age&#39;: [18, 99], &#39;sex&#39;: &#39;男&#39;, &#39;phone&#39;: 12345678}
Copy after login

11. dict.values()

values() 返回一个字典所有的值:
list1 = [&#39;Author&#39;, &#39;age&#39;, &#39;sex&#39;]
list2 = [&#39;Python当打之年&#39;, [18,99], &#39;男&#39;]
dic1 = dict(zip(list1, list2))
values = dic1.values()
print(&#39;values = &#39;, values)
print(type(values))
print(&#39;values = &#39;, list(values))

# values = dict_values([&#39;Python当打之年&#39;, [18, 99], &#39;男&#39;])
# <class &#39;dict_values&#39;>
# values = [&#39;Python当打之年&#39;, [18, 99], &#39;男&#39;]
Copy after login

The above is the detailed content of Basics | Detailed explanations of 11 Python dictionary usages. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

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.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

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 vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

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.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

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.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

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.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

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.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

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.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

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.

See all articles