Python字典是另一种可变容器模型(无序),且可存储任意类型对象,如字符串、数字、元组等其他容器模型。本文章主要介绍Python中字典(Dict)的详解操作方法,包含创建、访问、删除、其它操作等,需要的朋友可以参考下。
字典由键和对应值成对组成。字典也被称作关联数组或哈希表。基本语法如下:
1.创建字典
>>> dict = {'ob1':'computer', 'ob2':'mouse', 'ob3':'printer'} 技巧: 字典中包含列表:dict={'yangrong':['23','IT'],"xiaohei":['22','dota']} 字典中包含字典:dict={'yangrong':{"age":"23","job":"IT"},"xiaohei":{"'age':'22','job':'dota'"}} 注意: 每个键与值用冒号隔开(:),每对用逗号,每对用逗号分割,整体放在花括号中({})。 键必须独一无二,但值则不必。
2.访问字典里的值
>>> dict = {'ob1':'computer', 'ob2':'mouse', 'ob3':'printer'} >>> print(dict['ob1']) computer 如果用字典里没有的键访问数据,会输出错误如下: >>> print(dict['ob4']) Traceback (most recent call last): File "<pyshell#110>", line 1, in <module> print(dict['ob4']) 访问所有值 >>> dict1 = {'ob1':'computer', 'ob2':'mouse', 'ob3':'printer'} >>> for key in dict1: print(key,dict1[key]) ob3 printer ob2 mouse ob1 computer
3.修改字典
>>> dict = {'ob1':'computer', 'ob2':'mouse', 'ob3':'printer'} >>> dict['ob1']='book' >>> print(dict) {'ob3': 'printer', 'ob2': 'mouse', 'ob1': 'book'}
4.删除字典
能删单一的元素 >>> dict = {'ob1':'computer', 'ob2':'mouse', 'ob3':'printer'} >>> del dict['ob1'] >>> print(dict) {'ob3': 'printer', 'ob2': 'mouse'} 删除字典中所有元素 >>> dict1={'ob1':'computer','ob2':'mouse','ob1':'printer'} >>> dict1.clear() >>> print(dict1) {} 删除整个字典,删除后访问字典会抛出异常。 >>> dict1 = {'ob1':'computer', 'ob2':'mouse', 'ob3':'printer'} >>> del dict1 >>> print(dict1) Traceback (most recent call last): File "<pyshell#121>", line 1, in <module> print(dict1) NameError: name 'dict1' is not defined
5.更新字典
update()方法可以用来将一个字典的内容添加到另外一个字典中: >>> dict1 = {'ob1':'computer', 'ob2':'mouse'} >>> dict2={'ob3':'printer'} >>> dict1.update(dict2) >>> print(dict1) {'ob3': 'printer', 'ob2': 'mouse', 'ob1': 'computer'}
6.映射类型相关的函数
>>> dict(x=1, y=2) {'y': 2, 'x': 1} >>> dict8 = dict(x=1, y=2) >>> dict8 {'y': 2, 'x': 1} >>> dict9 = dict(**dict8) >>> dict9 {'y': 2, 'x': 1} dict9 = dict8.copy()
7.字典键的特性
字典值可以没有限制地取任何python对象,既可以是标准的对象,也可以是用户定义的,但键不行。 两个重要的点需要记住: 1)不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住 >>> dict1={'ob1':'computer','ob2':'mouse','ob1':'printer'} >>> print(dict1) {'ob2': 'mouse', 'ob1': 'printer'} 2)键必须不可变,所以可以用数,字符串或元组充当,用列表就不行 >>> dict1 = {['ob1']:'computer', 'ob2':'mouse', 'ob3':'printer'} Traceback (most recent call last): File "<pyshell#125>", line 1, in <module> dict1 = {['ob1']:'computer', 'ob2':'mouse', 'ob3':'printer'} TypeError: unhashable type: 'list'
8.字典内置函数&方法
Python字典包含了以下内置函数: 1、cmp(dict1, dict2):比较两个字典元素。(python3后不可用) 2、len(dict):计算字典元素个数,即键的总数。 3、str(dict):输出字典可打印的字符串。 4、type(variable):返回输入的变量类型,如果变量是字典就返回字典类型。 Python字典包含了以下内置方法: 1、radiansdict.clear():删除字典内所有元素 2、radiansdict.copy():返回一个字典的浅复制 3、radiansdict.fromkeys():创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值 4、radiansdict.get(key, default=None):返回指定键的值,如果值不在字典中返回default值 5、radiansdict.has_key(key):如果键在字典dict里返回true,否则返回false 6、radiansdict.items():以列表返回可遍历的(键, 值) 元组数组 7、radiansdict.keys():以列表返回一个字典所有的键 8、radiansdict.setdefault(key, default=None):和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default 9、radiansdict.update(dict2):把字典dict2的键/值对更新到dict里 10、radiansdict.values():以列表返回字典中的所有值
以上这篇python字典的常用操作方法小结就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.


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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1
Powerful PHP integrated development environment

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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool