search
HomeBackend DevelopmentPython TutorialPython中字典的基本知识初步介绍

 字典是可变的,并且可以存储任意数量的Python对象,包括其他容器类型另一个容器类型。字典包括键对(称为项目)及其相应的值。

Python字典也被称为关联数组或哈希表。字典的一般语法如下:

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

可以用下面的方式创建字典:

dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };

每个按键都来自它的值用冒号(:),该项目以逗号分隔,整个事情是包含在大括号分隔。没有任何项目一个空的字典是写只有两个大括号,就像这样:{}

键在一个字典中是唯一的,而值可能不是。字典的值可以是任何类型的,但键必须是不可变的数据类型,例如字符串,数字,或元组。
访问字典的值:

要访问字典元素,您可以使用熟悉的方括号一起的关键,获得它的值。下面是一个简单的例子:

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age'];

当执行上面的代码中,产生以下结果:

dict['Name']: Zara
dict['Age']: 7

如果要访问一个不存在的键,这会得到一个错误,如下所示:

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

print "dict['Alice']: ", dict['Alice'];

当执行上面的代码,产生以下结果:

dict['Zara']:
Traceback (most recent call last):
 File "test.py", line 4, in <module>
  print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'

更新字典:

可以通过添加一个新条目或项目(即一个键 - 值对),修改现有条目或删除。作为简单的例子,如下图所示在现有条目更新字词:

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry


print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];

当执行上面的代码,产生以下结果:

dict['Age']: 8
dict['School']: DPS School

删除字典元素:

可以删除单个字典元素或清除字典中的全部内容。也可以删除整个字典在一个单一的操作。

要删除整个字典,只要用del语句。下面是一个简单的例子:

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

del dict['Name']; # remove entry with key 'Name'
dict.clear();   # remove all entries in dict
del dict ;    # delete entire dictionary

print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];

这将产生以下结果。注意引发异常,这是因为经过del dict删除,字典已经不存在了:

dict['Age']:
Traceback (most recent call last):
 File "test.py", line 8, in <module>
  print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable

注:del()方法会在后续的章节中讨论。
字典的键的属性:

字典值没有限制。它们可以是任意Python对象,无论是标准的对象或用户定义的对象。但是作为键,是不可以这样的。

要记住字典中的键的两个要点:

(一)不准一个键对应多个条目。这意味着不能有重复的键。当有重复的键,在分配过程中以最后分配的为准。下面是一个简单的例子:

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};

print "dict['Name']: ", dict['Name'];

当执行上面的代码,产生以下结果:

dict['Name']: Manni

(二)键的值字必须是不可变的。这意味着可以使用字符串,数字或元组作为字典的键,但像['key']是不允许的。下面是一个简单的例子:

#!/usr/bin/python

dict = {['Name']: 'Zara', 'Age': 7};

print "dict['Name']: ", dict['Name'];

当执行上面的代码,产生以下结果:

Traceback (most recent call last):
 File "test.py", line 3, in <module>
  dict = {['Name']: 'Zara', 'Age': 7};
TypeError: list objects are unhashable

Statement
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
Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

How to improve the accuracy of jieba word segmentation in scenic spot comment analysis?How to improve the accuracy of jieba word segmentation in scenic spot comment analysis?Apr 02, 2025 am 07:09 AM

How to solve the problem of Jieba word segmentation in scenic spot comment analysis? When we are conducting scenic spot comments and analysis, we often use the jieba word segmentation tool to process the text...

How to use regular expression to match the first closed tag and stop?How to use regular expression to match the first closed tag and stop?Apr 02, 2025 am 07:06 AM

How to use regular expression to match the first closed tag and stop? When dealing with HTML or other markup languages, regular expressions are often required to...

How to get news data bypassing Investing.com's anti-crawler mechanism?How to get news data bypassing Investing.com's anti-crawler mechanism?Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

mPDF

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),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment