Python 字典完整指南

Python 字典完整指南

什么是字典、创建它们、访问它们、更新它们以及特殊方法

What are Dictionaries

在列表、集合和元组之后,字典是 Python 中准备好的下一个内置数据结构。它们通常用于编程,并为 Python 中许多不同库中更高级的结构和功能奠定了基础。它们采用类似于实际字典的形式,其中您具有具有值(描述)的键(词),因此采用键:值结构。它们的主要特点是:

  • 可变的:一旦定义它们就可以更改
  • 有序:除非明确更改,否则它们会保持顺序
  • 可索引:如果我们知道它们在字典中的位置(它们的键),我们就可以访问特定的项目
  • 没有重复的键:它们不能在键值中包含重复项,尽管它们可以在值中。

字典的重要部分是它们的键值结构,这意味着我们不是使用列表或元组中的数字索引来访问项目,而是使用它们的键来访问它们的值。然后,当我们可能想要使用特定键访问记录(例如销售记录或登录名)时,这允许使用字典。这比 List 或 Tuple 占用更多空间,但如果您知道可用于访问特定项的值的键,则可以进行更有效的搜索。

Implementation

由于键值关系,实现字典比创建列表、集合或元组要复杂一些。在这种情况下,主要有两种方式:

  • 使用 {} 表示法,但当我们的键和值由 : 分隔时,例如 {key:value}
  • 使用 dict() 函数,但仅当我们有一个包含两个项目的元组列表时

这里的关键是确保我们可以使用 key:value 结构创建字典,该结构可以如下创建:

#create a dict using {}
new_dict = {"Name":"Peter Jones",
"Age":28,
"Occupation":"Data Scientist"}
#create two lists
keys = ["Name", "Age", "Occupation"]
values = ["Sally Watson", 30, "Technical Director"]
#zip them together
zipped_lists = zip(keys, values)
#turn the zipped lists into a dictionary
new_dict2 = dict(zipped_lists)
#print the results
print(new_dict)
print(type(new_dict))
print("\n")print(new_dict2)
print(type(new_dict))
#out:
{'Name': 'Peter Jones', 'Age': 28, 'Occupation': 'Data Scientist'}



{'Name': 'Sally Watson', 'Age': 30, 'Occupation': 'Technical Director'}

我们可以看到我们已经能够使用这两种方法创建字典。

Datatypes

我们在上面已经看到,像列表、元组和集合字典可以包含多种不同的数据类型作为值,但它们也可以将不同的数据类型作为键,只要它们不可变,这意味着你不能使用列表或另一个字典作为键,因为它们是可变的。我们可以这样看:

mixed_dict = {"number":52,
"float":3.49,
"string":"Hello world",
"list":[12, "Cheese", "Orange", 52],
"Dictionary":{"Name":"Jemma",
"Age":23,
"Job":"Scientist"}}
print(type(mixed_dict))#out:

是一个有效的字典。

Accessing items

访问字典中的项目与访问列表或元组中的项目不同,因为现在我们使用键来访问值,而不是使用它们的数字索引。这意味着我们可以像以前一样使用 [] 表示法,但主要有两种方式:

  • 使用 [] 表示法指定我们要访问其值的键
  • 使用 get() 方法来指定我们想要访问值的键

它们之间的主要区别在于,如果键不在字典中,第一种方法会引发问题,而如果键不在字典中,第二种方法将简单地返回 None。方法的选择当然取决于你想对结果做什么,但每一个都可以按如下方式实现:

#the first way is as we would with a list
print(new_dict["Name"])
#however we can also use .get()
print(new_dict.get("Name"))
#the difference between the two is that for get if the key
#does not exist an error will not be triggered, while for
#the first method an error will be
#try for yourself:
print(new_dict.get("colour"))
#out:
Peter Jones
Peter Jones
None

以这种方式访问​​信息意味着我们不能在密钥中有重复项,否则我们将不知道我们正在访问什么。虽然在初始化字典时创建重复键不会产生错误消息,但它会影响您访问信息的方式。例如:

second_dict = {"Name":"William",
"Name":"Jessica"}
print(second_dict["Name"])#out:
Jessica

我们可以在这里设置两个“名称”键,当尝试访问信息时,它只打印第二个值,而不是第一个。这是因为第二个键覆盖了第一个键值。

Mutable

与列表和集合一样,与元组不同,字典是可变的,这意味着我们可以在创建字典后更改、添加或删除项目。我们可以以类似的方式执行此操作,即访问单个项目并使用变量赋值 ( = ) 来更改实际值。我们还可以通过简单地指定一个新键然后给它一个值(甚至不给它)来添加新的键:值对。最后,我们可以使用 update() 方法将新字典添加到现有字典中。这些都可以显示为:

#create the dictionary
car1 = {"Make":"Ford",
"Model":"Focus",
"year":2012}
#print the original year
print(car1["year"])
#change the year
car1["year"] = 2013
#print the new car year
print(car1["year"])
#add new information key
car1["Owner"] = "Jake Hargreave"
#print updated car ifnormation
print(car1)
#or we can add another dictionary
#to the existing dictionary using the update function
#this will be added to the end of the existing dictionary
car1.update({"color":"yellow"})
#this can also be used to update an existing key:value pair
#print updated versino
print(car1)
#out:
2012
2013
{'Make': 'Ford', 'Model': 'Focus', 'year': 2013, 'Owner': 'Jake Hargreave'}
{'Make': 'Ford', 'Model': 'Focus', 'year': 2013, 'Owner': 'Jake Hargreave', 'color': 'yellow'}

因此,我们可以更改字典中包含的信息,尽管除了删除它之外我们无法更改实际的键。因此,我们可以看到我们如何从字典中删除项目。

要从字典中删除项目,我们可以使用 del 方法,尽管我们必须小心这一点,否则我们可能会删除整个字典!我们还可以使用 pop() 方法来指定要从字典中删除的键。对此的扩展是 popitem() 方法,它在 Python 3.7+ 中从字典中删除最后一项(在此之前它是一个随机项)。最后,我们可以使用 clear() 方法从字典中删除所有值。这些可以实现为:

scores = {"Steve":68,
"Juliet":74,
"William":52,
"Jessica":48,
"Peter":82,
"Holly":90}
#we can use the del method
del scores["Steve"]
#although be careful as if you don't specify
#the key you can delete the whole dictionary
print(scores)#we can also use the pop method
scores.pop("William")
print(scores)#or popitem removes the last time
#(although in versinos before Python 3.7
#the removes a random item)
scores.popitem()
print(scores)#or we could empty the entire dictionary
scores.clear()
print(scores)#out:
{'Juliet': 74, 'William': 52, 'Jessica': 48, 'Peter': 82, 'Holly': 90}
{'Juliet': 74, 'Jessica': 48, 'Peter': 82, 'Holly': 90}
{'Juliet': 74, 'Jessica': 48, 'Peter': 82}
{}

Additional functionalities

由于我们的结构与列表、元组或集合的结构不同,因此字典也有自己的功能来处理这些问题。值得注意的是,您可以使用 keys() 方法从字典中提取所有键的列表,可以使用 values() 方法从字典中提取所有值的列表,并且可以使用 items() 方法提取键:值对的元组列表。最后,您还可以使用 len() 函数来提取字典的长度。我们可以这样看:

dictionary = {"Score1":12,
"Score2":53,
"Score3":74,
"Score4":62,
"Score5":88,
"Score6":34}
#access all the keys from the dictionary
print(dictionary.keys())
#access all the values form the dictionary
print(dictionary.values())
#access a tuple for each key value pair
print(dictionary.items())
#get the length of the dictionary
print(len(dictionary))
#out:
dict_keys(['Score1', 'Score2', 'Score3', 'Score4', 'Score5', 'Score6'])

dict_items([('Score1', 12), ('Score2', 53), ('Score3', 74), ('Score4', 62), ('Score5', 88), ('Score6', 34)])
6

这使您能够检查项目是否在键、值或两者中,同时还检查字典列表。

因此,一本完整的字典指南。字典具有键值结构的独特性质增加了字典的存储大小,但如果您知道与值相关联的键,它可以使检索更加准确,使其成为存储分层信息或跨区域信息的有价值的结构数据源。通过这种方式,它们为更复杂的数据存储方法(如 Pandas DataFrames、JSON 等)奠定了基础。

这是探索数据结构及其在 Python 中的使用和实现的系列文章中的第四篇。如果您错过了列表、元组和集合的前三个,您可以在以下链接中找到它们:

该系列的后续文章将涵盖 Python 中的链表、堆栈、队列和图。为确保您以后不会错过任何内容,请注册以在发布时接收电子邮件通知:

如果您喜欢您阅读的内容并且还不是 Medium 会员,请考虑通过使用下面的推荐代码注册来支持我自己和此平台上的其他出色作者:

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
扎眼的阳光的头像扎眼的阳光普通用户
上一篇 2022年4月25日
下一篇 2022年4月25日

相关推荐