Python 字典

Python 字典以键值对的方式存储数据,字典是可变的且不允许重复键的集合。早期的 Python 版本那种字典是无序的, 3.7 版本之后字典是有序的。

Python 字典以键值对的方式存储数据,字典是可变且的不允许重复键的集合。早期的 Python 版本那种字典是无序的, 3.7 版本之后字典是有序的。

字典是 Python 中用于存储数据集合的 4 种内置数据类型之一,其他 3 种是列表元组集合

创建 Python 字典的方式是使用字典字面量,和 JSON 结构很类似:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

Python 字典具有如下特征:

  • 字典通过键值对的方式存储数据。
  • 字典是可变的。
  • 字典中键不可以重复。
  • 字典中键值的数据类型可以不同。

字典类型

Python 字典的数据类型为 <class 'dict'>

打印字典的数据类型:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(type(thisdict)) # <class 'dict'>

访问项目

您可以使用方括号内的键名来访问字典的项目。

获取“model”键的值:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
x = thisdict["model"] # Mustang

也可以使用 get() 方法获取指定键的值:

x = thisdict.get("model") # Mustang

获取键值列表

keys() 方法将返回字典中所有键的列表(键列表不是普通的列表对象,它的类型是 <class 'dict_keys'>)。

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
x = thisdict.keys()
print(x) # dict_keys(['brand', 'model', 'year'])

键列表是字典的视图,对字典所做的任何更改都将反映在键列表中。

向原始字典添加一个新项目,并看到键列表也得到更新:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.keys()

print(x) # dict_keys(['brand', 'model', 'year'])

car["color"] = "white"
print(x) # dict_keys(['brand', 'model', 'year', 'color'])

获取值列表

values() 方法将返回字典中所有值的列表(值列表不是普通的列表对象,它的类型是 <class 'dict_values'>)。

值列表是字典的视图,对字典所做的任何更改都将反映在值列表中。

在原始字典中进行更改,并看到值列表也得到更新:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.values()

print(x) # dict_values(['Ford', 'Mustang', 1964])

car["year"] = 2020
car["color"] = "red"
print(x) # dict_values(['Ford', 'Mustang', 2020, 'red'])

获取键值对列表

items() 方法将返回字典中的所有键值对的列表(键值对列表不是普通的列表对象,它的类型是 <class 'dict_items'>)。

返回的列表是字典的视图,对字典所做的任何更改都将反映在项列表中。

在原始字典中进行更改,并看到项目列表也得到更新:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.items()

print(x) # dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])

car["year"] = 2020
car["color"] = "red"
print(x) # dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 2020), ('color', 'red')])

检查键是否存在

要确定字典中是否存在指定的键,请使用 in 关键字。

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
if "model" in thisdict:
  print("Yes, 'model' is one of the keys in the thisdict dictionary")

更改值

通过引用其键名来更改特定键的值。当给定的键值不存在时,会新增键值对数据。

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict["year"] = 2018
thisdict["color"] = "red"
print(thisdict) # {'brand': 'Ford', 'model': 'Mustang', 'year': 2018, 'color': 'red'}

更新字典

update() 方法将使用给定参数中的项目更新字典,参数必须是字典或具有键值对的可迭代对象。

如果字典中不存在参数中的键,则会添加键值对数据;如果字典中存在参数中的键,则会更新键的值。

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.update({"year": 2020, "color": "red"})
print(thisdict) # {'brand': 'Ford', 'model': 'Mustang', 'year': 2020, 'color': 'red'}

删除项目

有几种方法可以从字典中删除项目:

pop() 方法根据指定的键值删除项目:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.pop("model")
print(thisdict) # {'brand': 'Ford', 'year': 1964}

popitem() 方法删除最后插入的项目(在 3.7 之前的版本中不保证删除哪一个):

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.popitem()
print(thisdict) # {'brand': 'Ford', 'model': 'Mustang'}

del 关键字也可以删除与指定键的项目:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
del thisdict["model"]
print(thisdict) # {'brand': 'Ford', 'year': 1964}

del 关键字也可以完全删除字典:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
del thisdict
print(thisdict) # NameError: name 'thisdict' is not defined

clear() 方法清空字典:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.clear()
print(thisdict) # {}

遍历字典

可以使用 for...in 循环遍历字典。

遍历字典中的所有键:

for x in thisdict:
  print(x)

遍历字典中的所有值:

for x in thisdict:
  print(thisdict[x])

遍历字典中的键值对:

for x, y in thisdict.items():
  print(x, y)

复制字典

有多种方法可以复制字典,最简单的方法是使用内置的 copy() 方法。

使用以下 copy() 方法制作字典的副本:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
mydict = thisdict.copy()
print(mydict) # {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

制作副本的另一种方法是使用构造函数 dict() 重新构造一个字典。

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
mydict = dict(thisdict)
print(mydict) # {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

嵌套字典

字典可以包含字典,这称为嵌套字典。

创建一个包含三个字典的字典:

myfamily = {
  "child1" : {
    "name" : "Emil",
    "year" : 2004
  },
  "child2" : {
    "name" : "Tobias",
    "year" : 2007
  },
  "child3" : {
    "name" : "Linus",
    "year" : 2011
  }
}

或者,创建三个字典,然后创建一个包含其他三个字典的字典:

child1 = {
  "name" : "Emil",
  "year" : 2004
}
child2 = {
  "name" : "Tobias",
  "year" : 2007
}
child3 = {
  "name" : "Linus",
  "year" : 2011
}

myfamily = {
  "child1" : child1,
  "child2" : child2,
  "child3" : child3
}

Python 字典方法

字典方法

Python 有一组内置方法,您可以在字典中使用它们。

方法 说明
clear() 清空字典
copy() 复制字典
fromkeys() 根据指定的键返回一个字典
get() 返回指定键的值
items() 返回字典的键值对列表
keys() 返回字典的键列表
values() 返回字典的值列表
pop() 根据指定的键删除一个项目
popitem() 删除最有一个键值对
setdefault() 返回指定键的值,如果键不存在插入这个键和指定的默认值
update() 更新字典