Python 字典


字典是一个无序的集合,包含用逗号分隔的花括号内的key:value对。 字典经过优化,可以在已知关键字的情况下检索值。

下面声明一个字典对象。

Example: Dictionary

capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New Delhi"}

上图,capitals是一个字典对象,其中包含{ }内部的键值对。 左侧:为按键,右侧为数值。 密钥应该是唯一且不可变的对象。数字、字符串或元组可以用作关键字。因此,以下词典也有效:

Example: Dictionary Objects

d = {} # empty dictionary

numNames={1:"One", 2: "Two", 3:"Three"} # int key, string value

decNames={1.5:"One and Half", 2.5: "Two and Half", 3.5:"Three and Half"} # float key, string value

items={("Parker","Reynolds","Camlin"):"pen", ("LG","Whirlpool","Samsung"): "Refrigerator"} # tuple key, string value

romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5} # string key, int value 

但是,以列表作为关键字的字典是无效的,因为列表是可变的:

Error: List as Dict Key

dict_obj = {["Mango","Banana"]:"Fruit", ["Blue", "Red"]:"Color"}

但是,列表可以用作值。

Example: List as Dictionary Value

dict_obj = {"Fruit":["Mango","Banana"], "Color":["Blue", "Red"]} 

同一个键在集合中不能出现多次。如果该密钥出现多次,将只保留最后一次。该值可以是任何数据类型。一个值可以分配给多个键。

Example: Unique Keys

>>> numNames = {1:"One", 2:"Two", 3:"Three", 2:"Two", 1:"One"}
>>> numNames
{1:"One", 2:"Two", 3:"Three"} 

dict是所有字典的类,如下图所示。

Example: Distinct Type

>>> numNames = {1:"One", 2:"Two", 3:"Three", 2:"Two", 1:"One"}
>>> type(numNames)
<class 'dict'> 

也可以使用 dict() 构造器方法创建字典。

Example: dict() Constructor Method

>>> emptydict = dict()
>>> emptydict
{}
>>> numdict = dict(I='one', II='two', III='three')
>>> numdict
{'I': 'one', 'II': 'two', 'III': 'three'} 

访问字典

字典是一个无序的集合,因此不能使用索引访问值;相反,必须在方括号中指定一个键,如下所示。

Example: Get Dictionary Values

>>> capitals = {"USA":"Washington DC", "France":"Paris", "India":"New Delhi"}
>>>capitals["USA"]
'Washington DC'
>>> capitals["France"]
'Paris'
>>> capitals["usa"]  # Error: Key is case-sensitive
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    capitals['usa']
KeyError: 'usa'
>>> capitals["Japan"] # Error: key must exist
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
capitals['Japan']
KeyError: 'Japan' 

*Note:*Keys are case-sensitive. So, usa and USA are treated as different keys. If the specified key does not exist then it will raise an error. *使用 get() 方法检索键的值,即使键是未知的。 如果密钥不存在,则返回None,而不是产生错误。

Example: Get Dictionary Values

>>> capitals = {"USA":"Washington DC", "France":"Paris", "Japan":"Tokyo", "India":"New Delhi"}
>>> capitals.get("USA")
'Washington DC'
>>> capitals.get("France")
'Paris'
>>> capitals.get("usa")
>>> capitals.get("Japan")
>>> 

使用 for循环访问字典

使用 for循环迭代 Python 脚本中的字典。

Example: Access Dictionary Using For Loop

capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New Delhi"}

for key in capitals:
    print("Key = " + key + ", Value = " + capitals[key]) 

Output

Key = 'USA', Value = 'Washington D.C.'
Key = 'France', Value = 'Paris'        
Key = 'India', Value = 'New Delhi' 

更新词典

如前所述,密钥不能出现多次。使用相同的键并为其分配新值,以更新字典对象。

Example: Update Value of Key

>>> captains = {"England":"Root", "Australia":"Smith", "India":"Dhoni"}
>>> captains['India'] = 'Virat'
>>> captains['Australia'] = 'Paine'
>>> captains
{'England': 'Root', 'Australia': 'Paine', 'India': 'Virat'} 

使用新的键并为其赋值。字典将在其中显示一个额外的键值对。

Example: Add New Key-Value Pair

>>> captains['SouthAfrica']='Plessis'
>>> captains
{'England': 'Root', 'Australia': 'Paine', 'India': 'Virat', 'SouthAfrica': 'Plessis'} 

从字典中删除值

使用 del 关键字、 pop() 或 popitem() 方法从字典或字典对象本身中删除一对。要删除一对,请使用其键作为参数。 要删除字典对象,请使用其名称。

Example: Delete Key-Value

>>> captains = {'England': 'Root', 'Australia': 'Paine', 'India': 'Virat', 'Srilanka': 'Jayasurya'}
>>> del captains['Srilanka'] # deletes a key-value pair
>>> captains
{'England': 'Root', 'Australia': 'Paine', 'India': 'Virat'}
>>> del captains # delete dict object
>>> captains
NameError: name 'captains' is not defined 

NameError表示字典对象已经从内存中移除。

检索字典键和值

键()和值()方法分别返回包含键和值的视图对象。

Example: keys()

>>> d1 = {'name': 'Steve', 'age': 21, 'marks': 60, 'course': 'Computer Engg'}
>>> d1.keys()
dict_keys(['name', 'age', 'marks', 'course'])
>>> d1.values()
dict_values(['Steve', 21, 60, 'Computer Engg']) 

检查字典键

您可以使用in或not in关键字检查字典集合中是否存在主键,如下所示。 注意,它只检查键,不检查值。

Example: Check Keys

>>> captains = {'England': 'Root', 'Australia': 'Paine', 'India': 'Virat', 'Srilanka': 'Jayasurya'}
>>> 'England' in captains
True
>>> 'India' in captains
True
>>> 'France' in captains
False
>>> 'USA' not in captains
True 

多维词典

让我们假设有三个字典对象,如下所示:

Example: Dictionary

>>> d1={"name":"Steve","age":25, "marks":60}
>>> d2={"name":"Anil","age":23, "marks":75}
>>> d3={"name":"Asha", "age":20, "marks":70} 

让我们给这些学生分配卷号,创建一个以卷号为关键字的多维字典,并根据它们的值对上述字典进行排序。

Example: Multi-dimensional Dictionary

>>> students={1:d1, 2:d2, 3:d3}
>>> students
{1: {'name': 'Steve', 'age': 25, 'marks': 60}, 2: {'name': 'Anil', 'age': 23, 'marks': 75}, 3: {'name': 'Asha', 'age': 20, 'marks': 70}}< 

student对象是一个二维字典。这里d1、d2和d3分别被指定为键 1、2 和 3 的值。students[1]返回d1。

Example: Access Multi-dimensional Dictionary

>>> students[1]
{'name': 'Steve', 'age': 25, 'marks': 60}
>>> students[1]['age']
25 

内置字典方法

方法 描述
dict.clear() 从字典中移除所有键值对。
dict.copy() 返回字典的一个简单副本。
发布 fromkeys() 从给定的可迭代表(字符串、列表、集合、元组)创建一个新的字典作为键,并使用指定的值。
dict.get() 返回指定键的值。
dict.items() 返回字典视图对象,该对象以键值对列表的形式提供字典元素的动态视图。当字典改变时,这个视图对象也随之改变。
dict . key() 返回包含字典键列表的字典视图对象。
dict.pop() 移除键并返回其值。如果字典中不存在某个键,则返回默认值(如果指定的话),否则将引发键错误。
关闭。泼皮() 从字典中移除并返回(键、值)对的元组。成对按后进先出(后进先出)顺序返回。
dict.setdefault() 返回字典中指定键的值。如果找不到该键,则添加具有指定 defaultvalue 的键。如果未指定默认值,则设置为无值。
dict.update() 使用来自另一个字典或另一个表(如具有键值对的元组)的键值对更新字典。
字典值() 返回字典视图对象,该对象提供字典中所有值的动态视图。当字典 改变时,这个视图对象改变。

评论关闭