geekdoc-python-zh/docs/pythonguru/010.md

3.8 KiB
Raw Permalink Blame History

Python 字典

原文: https://thepythonguru.com/python-dictionaries/


于 2020 年 1 月 7 日更新


字典是一种 python 数据类型,用于存储键值对。 它使您可以使用键快速检索,添加,删除,修改值。 字典与我们在其他语言上称为关联数组或哈希的非常相似。

注意

字典是可变的。

创建字典


可以使用一对大括号({})创建字典。 字典中的每个项目都由一个键,一个冒号,一个值组成。 每个项目都用逗号(,)分隔。 让我们举个例子。

friends = {
'tom' : '111-222-333',
'jerry' : '666-33-111'
}

这里friends是有两个项目的字典。 需要注意的一点是,键必须是可哈希的类型,但是值可以是任何类型。 字典中的每个键都必须是唯一的。

>>> dict_emp = {} # this will create an empty dictionary

检索,修改和向字典中添加元素


要从字典中获取项目,请使用以下语法:

>>> dictionary_name['key']

>>> friends['tom']
'111-222-333'

如果字典中存在键,则将返回值,否则将引发KeyError异常。 要添加或修改项目,请使用以下语法:

>>> dictionary_name['newkey'] = 'newvalue'

>>> friends['bob'] = '888-999-666'
>>> friends
 {'tom': '111-222-333', 'bob': '888-999-666', 'jerry': '666-33-111'}

从字典中删除项目


>>> del dictionary_name['key']

>>>  del friends['bob']
>>>  friends
{'tom': '111-222-333', 'jerry': '666-33-111'}

如果找到键,则该项目将被删除,否则将抛出KeyError异常。

遍历字典中的项目


您可以使用for循环遍历字典中的元素。

>>> friends = {
... 'tom' : '111-222-333',
... 'jerry' : '666-33-111'
...}
>>>
>>> for key in friends:
...     print(key, ":", friends[key])
...
tom : 111-222-333
jerry : 666-33-111
>>>
>>>

查找字典的长度


您可以使用len()函数查找字典的长度。

>>> len(friends)
2

innot in运算符


innot in运算符检查字典中是否存在键。

>>> 'tom' in friends
True
>>> 'tom' not in friends
False

字典中的相等测试


==!=运算符告诉字典是否包含相同的项目。

>>> d1 = {"mike":41, "bob":3}
>>> d2 = {"bob":3, "mike":41}
>>> d1 == d2
True
>>> d1 != d2
False
>>>

注意

您不能使用<>>=<=等其他关系运算符来比较字典。

字典方法


Python 提供了几种内置的方法来处理字典。

方法 描述
popitem() 返回字典中随机选择的项目,并删除所选项目。
clear() 删除字典中的所有内容
keys() 以元组形式返回字典中的键
values() 以元组形式返回字典中的值
get(key) 键的返回值,如果找不到键,则返回None,而不是引发KeyError异常
pop(key) 从字典中删除该项目,如果找不到该键,则会抛出KeyError
>>> friends = {'tom': '111-222-333', 'bob': '888-999-666', 'jerry': '666-33-111'}
>>>
>>> friends.popitem()
('tom', '111-222-333')
>>>
>>> friends.clear()
>>>
>>> friends
{}
>>>
>>> friends = {'tom': '111-222-333', 'bob': '888-999-666', 'jerry': '666-33-111'}
>>>
>>> friends.keys()
dict_keys(['tom', 'bob', 'jerry'])
>>>
>>> friends.values()
dict_values(['111-222-333', '888-999-666', '666-33-111'])
>>>
>>> friends.get('tom')
'111-222-333'
>>>
>>> friends.get('mike', 'Not Exists')
'Not Exists'
>>>
>>> friends.pop('bob')
'888-999-666'
>>>
>>> friends
{'tom': '111-222-333', 'jerry': '666-33-111'}

在下一篇文章中,我们将学习 Python 元组