Python - 字典

2023-09-17 22:16:26

字典是一个无序集合,其中包含key:value对,由大括号内的逗号分隔。 字典经过优化,可在密钥已知时检索值。

下面声明一个字典对象。

capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New Delhi"}
print(type(capitals))  #output: <class 'dict'>

上面,capitals是一个字典对象,其中包含{ }内的键值对。 :的左侧是键,右侧是值。 键应该是唯一的,并且是不可变的对象。字典类是 dict

数字、字符串或元组可以用作键。因此,以下词典也是有效的:

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

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

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

但是,列表可以用作值。

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

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

numNames = {1:"One", 2:"Two", 3:"Three", 2:"Two", 1:"One", 2:"Two"}
print(numNames)  #output: {1:"One", 2:"Two", 3:"Three"}

还可以使用 dict() 构造函数方法创建字典。

emptydict = dict()
numdict = dict(I='one', II='two', III='three')

访问词典(Access Dictionary)

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

numNames={1:"One", 2: "Two", 3:"Three"}
print(numNames[1], numNames[2], numNames[3],) #output:One Two Three
capitals = {"USA":"Washington DC", "France":"Paris", "India":"New Delhi"}
print(capitals["USA"], capitals["France"],)  #output:Washington DC Paris
#following throws an KeyError
#print(capitals["usa"])
#print(capitals["Japan"])

注意: 键区分大小写。因此,usaUSA被视为不同的键。如果指定的键不存在,则会引发错误。

使用 get() 方法检索键的值,即使键未知。 如果密钥不存在,它会返回None,而不是引发错误。

numNames={1:"One", 2: "Two", 3:"Three"}
print(numNames.get(1), numNames.get(2),numNames.get(3))
capitals = {"USA":"Washington DC", "France":"Paris", "India":"New Delhi"}
print(capitals.get("USA"), capitals.get("France"))
#following throws an KeyError
#print(capitals.get("usa"))
#print(capitals.get("Japan"))

使用 For 循环访问字典(Access Dictionary using For Loop)

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

capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New Delhi"}
for key in capitals:
    print("Key = " + key + ", Value = " + capitals[key]) 

输出:

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

更新词典(Update Dictionary)

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

captains = {"England":"Root", "Australia":"Smith", "India":"Dhoni"}
print(captains)
captains['India'] = 'Virat'
captains['Australia'] = 'Paine'
print(captains)  #output: {'England': 'Root', 'Australia': 'Paine', 'India': 'Virat'}

如果您使用新键并为其赋值,则它将在字典中添加一个新的键值对。

captains = {"England":"Root", "India":"Dhoni"}
captains['SouthAfrica']='Plessis'
print(captains) #output: {'England': 'Root', 'India': 'Virat', 'SouthAfrica': 'Plessis'}

从字典中删除值(Deleting Values from a Dictionary)

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

captains = {'Australia': 'Paine', 'India': 'Virat', 'Srilanka': 'Jayasurya'}
print(captains)
del captains['Australia'] # deletes a key-value pair
print(captains)
del captains # delete dict object
#print(captains) #error

检索字典键和值 (Retrieve Dictionary Keys and Values )

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

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

检查字典键(Check Dictionary Keys)

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

captains = {'England': 'Root', 'Australia': 'Paine', 'India': 'Virat', 'Srilanka': 'Jayasurya'}
b = 'England' in captains
print(b) #True
b = 'India' in captains
print(b)  #True
b = 'France' in captains
print(b)  #False

多维字典(Multi-dimensional Dictionary)

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

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

让我们为这些学生分配卷号,并创建一个多维字典,以卷号为键,上述字典的值为键。

students={1:d1, 2:d2, 3:d3}
print(students) #{1: {'name': 'Steve', 'age': 25, 'marks': 60}, 2: {'name': 'Anil', 'age': 23, 'marks': 75}, 3: {'name': 'Asha', 'age': 20, 'marks': 70}}
print(students[1]) # {'name': 'Steve', 'age': 25, 'marks': 60}
print(students[2]) # {'name': 'Anil', 'age': 23, 'marks': 75}
print(students[3]) # {'name': 'Asha', 'age': 20, 'marks': 70}

student对象是一个二维字典。这里d1d2d3分别作为值分配给键 1、2 和 3。students[1]返回d1

内置字典方法(Built-in Dictionary Methods)

函数描述
dict.clear() 从字典中删除所有键值对。
dict.copy() 返回字典的浅表副本。
dict.fromkeys() 从给定的可迭代对象(字符串、列表、集合、元组)作为键并使用指定的值创建新字典。
dict.get() 返回指定键的值。
dict.items() 返回一个字典视图对象,该对象以键值对列表的形式提供字典元素的动态视图。此视图对象在字典更改时更改。
dict.keys() 返回一个包含字典的键列表的dictionary view object
dict.pop() 删除密钥并返回其值。如果字典中不存在键,则返回默认值(如果指定),否则将引发 KeyError。
dict.popitem() 从字典中删除并返回(键、值)对的元组。对按后进先出 (LIFO) 顺序返回。
dict.setdefault() 返回字典中指定键的值。如果未找到该键,则添加具有指定默认值的键。如果未指定默认值,则设置"无"值。
dict.update() 使用来自另一个字典或其他可迭代对象(如具有键值对的元组)的键值对更新字典。
dict.values() 返回提供字典中所有值的动态视图的dictionary view object。此视图对象在字典更改时更改 变化。

本文内容总结: