Python字典的介绍

291 阅读13分钟

字典在Python中是必不可少的,因为它的引入代表了编程的一个重大进步。在字典之前,编程要困难得多;你必须把所有的数据保存在列表或数组中,并记住哪个索引是哪个数据的,这就造成了非常容易出错的程序。

为了更快地找到数值,开发人员必须对列表进行排序,并利用二进制搜索,如果数据是动态的,开发人员必须不断求助。这个过程经常导致非常迟缓的代码,需要进一步注意。

然而,Python字典解决了这个问题。

Python中的字典是一种数据类型,它以一种无序的方式存储变量,其中的值被映射到一个键上,并可以使用每项的键轻松访问。key 是一个不可改变的元素,代表 dictionary 中的一个值。

在这篇文章中,你将了解什么是 Python 中的字典,它们的属性,你可以对它们进行的操作,以及一些内置的 Python 函数和方法,以便与字典一起工作。

Python 字典的属性

Python 字典拥有一些明显的行为,使它与其它数据结构不同。这些属性包括

  • 不可变的字典键
  • 一个无序的数据集合
  • 多种数据类型的值
  • 键的数据类型可以是数字、字符串、浮点数、布尔值、图元,以及像类和函数这样的内置对象

此外,字典的键必须是唯一的。如果在一个字典中定义了一个重复的键,Python 会考虑最后一个重复的。

Python 的字典操作

在 Python 中声明一个 dictionary

在 Python 中,你可以通过用大括号包裹一连串的值对 (格式为key: value 的 key 和 key-value) 来声明一个 dictionary,并以逗号分隔。

dict = {"first-key":1,"second-key":2}

你也可以用空的大括号定义一个空的 dictionary,如下面的代码片断所示。

dict = {}

检索 Python dictionary 中的一个项目

要获取一个 dictionary 中的一个项的值,在方括号中输入 dictionary 名称和项的键。

# declared the dictionary
dict = {"first-key":1,"second-key":2}

# retrieved a value from the dictionary
dict["first-key"]
dict["second-key"]


# your result should be 1 and 2

在这里,你可以访问与方括号中输入的键名相关的值,它存在于字典中 (dict)。

插入或更新一个 Python 字典项目

在 dictionary 中插入或更新一个项是用append() 函数完成的。这个函数在检查是否插入或用它来更新值之前,会收集你想在 dictionary 中插入的键和值。

# declared the dictionary
dict= {"first-key":1,"second-key":2}

# inserting an item in the dictionary using append()
dict["third-key"].append (3)

# inserting an item in the dictionary without using append()
dict["third-key"] = 3

print(dict)

# output item was created
 # {"first-key":1,"second-key":2, "third-key":3}

通过使用append 函数在字典中插入一个值 (dict),该函数使用在字典方括号中输入的键来注册在append 函数括号中输入的值。

然而,如果指定的键已经存在于 dictionary 中,Python 只在适当的地方更新 dictionary 中的值。

# declared the dictionary
dict= {"first-key":1,"second-key":2,"third-key":3}

# updating an item in the dictionary using append()

dict["third-key"].append (4)
    
    # updating an item in the dictionary without append()
dict["third-key"] = 4

    print(dict)
    # output  value for key updated
    # {"first-key":1,"second-key":2, "third-key":4}

由于我们在方括号中输入的键已经存在于字典中 (dict),与该键相关的值被更新为在append 函数的括号中输入的新值。

删除 Python dictionary 中的项目

你也可以从 dictionary 中删除一个项目,方法是用 key 检索这个项目,用del() 命令删除这个项目,如下面的代码片段所示。

# declared the dictionary
dict= {"first-key":1,"second-key":2,"third-key":3}

#retrieve and delete an item in the dictionary
del(dict["third-key"])
    
    print(dict)
    #output  value for key updated
    {"first-key":1,"second-key":2}

在这里,我们用del 函数从 dictionary 中删除了与方括号中指定的 key 相关的项。

你也可以删除整个 dictionary,如下面的代码所示。

dict= {"first-key":1,"second-key":2,"third-key":3}

#delete entire dictionary
del(dict)

循环浏览 Python dictionary 中的项目

循环在 Python 中可用来执行复杂的字典操作,比如删除所有带空键的项目,从嵌套的字典中检索数据,反转字典中的值,等等。

从本质上讲,循环有助于将复杂的字典操作分解成若干步骤,使它们更容易完成。

下面是一个利用循环来逐一检索一个字典中的项目的例子。

# declaring the dictionary
dict =  {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
 #looping through items keys in the dictionary
for x in thisdict:
  print(x)

#output
    # brand
    # model
      # year


 #looping through item values in the dictionary
for x in thisdict:
  print(thisdict[x])

#output
    # Ford
    # Mustang
            # 1964

这里的第一个例子描述了如何通过循环来访问和打印项目的键,而第二个例子则描述了如何访问和打印其值。

Python 中的嵌套字典

我们在前面说过,我们可以在 dictionary 中的一个项目的 key-value 中插入任何数据类型。然而,一个嵌套的 dictionary 有另一个 dictionary 作为它的 key-value。

当你必须用一个特定的键将一组项目作为一个整体进一步关联时,你可以使用嵌套的 dictionary,同时将每个项目与它们的键关联起来。这方面的一个例子是把桔子联结为柑橘,把蓝莓联结为浆果,然后再把它们进一步分组为水果。

让我们看看如何用这个例子声明一个嵌套的字典。

# declaring the nested dictionary
products = {"fruits":{"citrus":"orange","berry":"blueberry"}, "gadgets":{"laptop":"macbook","phone":"iphone"}}

在上面的代码示例中,我们可以将两个字典作为项目与另一个字典中的特定键联系起来。覆盖其他字典的字典被称为父字典。

在下一节,你将学习如何检索一个嵌套的 dictionary 的项。

检索 Python 嵌套字典中的一个项目

要从一个嵌套的 dictionary 中检索一个项,必须使用两个或更多的键来获得所需的键值,这取决于 dictionary 所包含的嵌套的数量。

例如,如果父级 dictionary 包含一个 dictionary 层,你需要两个键来检索项的值。下面是一个例子,说明如何用键来检索一个键值。

# declaring the single nested dictionary
products = {"fruits":{"citrus":"orange","berry":"blueberry"}, "gadgets":{"laptop":"macbook","phone":"iphone"}}

# get the laptop value
print(products["gadgets"]["laptop"])
print(products["fruits"]["citrus"])

# output 
# macbook
# orange

在上面的代码示例中,我们只需要两个方括号来检索项值,因为 dictionary 只有一个巢穴。

在 dictionary 有两个 nest 的情况下,我们必须使用三个方括号来检索项目值。下面是一个双嵌套 dictionary 的例子。

# declaring the double nested dictionary
creatures = {"animal":{"mammal":{"human": "baby"}}, "plant":{"seeds":{"flower":"sun flower"}}}

# get the laptop value
print(creatures["animal"]["mammal"]["human"])
print(creatures["plant"]["seeds"]["flower"])


# output 
# baby
# sun flower

在 Python 嵌套的 dictionary 中插入或更新一个项目

要在一个嵌套的 dictionary 中插入一个项,必须给 dictionary 赋值或追加一个 key 和一个值。如果这个项的 key 已经存在于 dictionary 中,那么只有 key-value 的更新。否则,该项目就插入到 dictionary 中。

下面是一个代码例子,显示如何在一个嵌套的 dictionary 中插入或更新一个项目。

# declaring the nested dictionary
products = {"fruits":{"citrus":"orange","berry":"blueberry"}, "gadgets":{"laptop":"macbook","phone":"iphone"}}

# inserting or updating using append
new_item={"shirt": "sleeves", "socks":"short socks"}
products["clothes"].append(new_item)

# inserting or updating without append
new_item={"shirt": "sleeves", "socks":"short socks"}
products["clothes"].append(new_item)

print(products)

# output
# {"fruits":{"citrus":"orange","berry":"blueberry"}, "gadgets":{"laptop":"macbook","phone":"iphone"}, 
"clothes": {"shirt": "sleeves", "socks":"short socks"}
}

在这里,我们声明了一个名为products 的单一嵌套的 dictionary 。为了向products 词典中添加项目,我们向append 函数传递一个新的词典。然后新的 dictionary 可以作为一个项被添加到products 的父 dictionary 中。

从 Python 嵌套的 dictionary 中删除一个项

要从一个嵌套的 dictionary 中删除一个项,必须先用 key 检索这个项,然后用del() 方法删除这个项。

与非嵌套字典上的删除操作不同的是,通过将嵌套字典中的一个字典或键传递给delete 函数来删除,可以将字典和值都作为项目来删除。

下面是一个使用 Python 从嵌套的 dictionary 中删除一个项的例子。如果我们声明一个products 嵌套的 dictionary,我们可以将一个 dictionary 传给delete 函数,它将从嵌套的 dictionary 中删除。

# declaring the nested dictionary
products = {"fruits":{"citrus":"orange","berry":"blueberry"}, "gadgets":{"laptop":"macbook","phone":"iphone"}}


# deleting the laptop  item 
del(products["gadgets"]["laptop"])

print(products)

#output
# products = {"fruits":{"citrus":"orange","berry":"blueberry"}, "gadgets":{"phone":"iphone"}}

Python 的字典函数

Python 函数有特定的用途,有助于减轻你作为一个开发者的工作,因为它使你能够构建可重用的代码。下面是一些内置的 Python 函数,你可以用来对 dictionary 进行简单的操作。

cmp(dict1, dict2) 函数

cmp() 函数对两个字典进行比较,找出它们的值是否相等。如果它们的值相等,则返回0 的响应。

例如,如果我们创建了四个字典,我们可以用cmp 函数来比较它们。

# declared 4 dictionaries
dict1 = {"name":"john","age":18}
dict2 = {"name":"Mary","age":12} 
dict3 = {"name":"Lisa","age":12}
dict4 = {"name":"john","age":18}

#comparing the dictionaries
print("value returned : %d" %  cmp (dict1, dict2))
print("value returned : %d" %  cmp (dict2, dict3))
    print("value returned : %d" %  cmp (dict1, dict4))
    
    # output
    # value returned: -1
    # value returned: 1
    # value returned: 0

比较dict1dict2 ,返回的输出是-1 ,因为它们里面没有类似的东西。

然而,比较dict2dict3 ,返回的结果是1 ,因为它们有相同的年龄值;比较dict1dict4 ,返回的结果是0 ,因为它们有所有相同的值,如前所述。

len(dict) 函数

len() 函数得到它所传递的字典的长度,并返回一个列表中的项目总数。这句话意味着,如果一个 dictionary 有三个项目,那么它的长度就是3

你可以用这个函数来查找任何字典的长度。

# declared dictionary
dict = {"name":"john","age":18, "weight": "65kg"}

# get the length of dict
print("The length of dict is: %d" % len(dict))

#output
# The length of dict is: 3

Thestr(dict) 函数

str(dict) 函数可以得到它所传递的一个字典的可打印字符串表示。当你想把字典打印成字符串时,你可以使用它。

# declared dictionary
dict = {"name":"john","age":18, "weight": "65kg"}

# get the str representation of dict
print("The string equivalent of dict is: %s" % str(dict))

#output
# The string equivalent of dict is {'name': 'john', 'age': 18, 'weight': '65kg'}

Thetype() 函数

type() 函数可以返回它所传递的一个变量的数据类型。如果你在type() 函数中传递一个 dictionary,它将返回一个dict 数据类型。你可以用这个函数来了解任何变量的数据类型。

# declare dictionary
dict = {"name":"john","age":18, "weight": "65kg"}


# return the data type
print("Data Type : %s" %  type (dict))

# output
# Data Type: <type 'dict'>

Python 的字典方法

Python 方法,类似于我们前面看到的函数,允许你重复使用并执行预先建立的操作。下面是一些内置的 Python 方法,你可以用来对字典进行操作。

dict.clear() 方法

dict.clear() 方法从 dictionary 中删除所有的项目,返回一个空的 dictionary。当你想快速清空你的 dictionary 以获得一片净土时,你可以使用这个方法。下面是一个使用clear() 方法的例子。

# declare the dictionary
dict = {'Name': 'Andrew', 'Age': 7};

# delete all items in the dictionary
dict.clear()

print("Dictionary : %s" %  str(dict))

# output 
# Dictionary : {}

dict.copy() 方法

copy() 方法得到一份传递给它的 dictionary 的副本。当你不想从头开始创建一个字典时,你可以使用它。它还可以减少从当前字典中逐项复制到新字典的压力。

# declare the dictionary
dict1 = {'Name': 'Andrew', 'Age': 7}

# make a copy of the dictionary
dict2 = dict1.copy()

print("New Dictionary : %s" %  str(dict2))

# output 
# New Dictionary : {'Name': 'Andrew', 'Age': 7}

通过创建一个 dictionary (dict1),然后用copy 方法在dict2 中进行复制,你可以从输出中看到两个 dictionary 有相同的值。

dict.fromkey() 方法

dict.fromkey() 方法可以从一个值的序列中创建一个字典。当创建一个 dictionary 时,序列中的每个值都成为 dictionary 中的一个 key。

你可以用这个方法用你还没有值的键来创建一个 dictionary。这是按dict.fromkeys(seq[, value]) 语法进行的。

# create a sequence
seq = ('name', 'age', 'sex')

#create a dictionary from the sequence
dict = dict.fromkeys(seq)

print("New Dictionary : %s" %  str(dict))

dict = dict.fromkeys(seq, 10)
print("New Dictionary : %s" %  str(dict))

#output
# New Dictionary : {'age': None, 'name': None, 'sex': None}
# New Dictionary : {'age': 10, 'name': 10, 'sex': 10}

在上面的代码示例中,我们可以使用fromkeys() 方法从一个包含键值序列的变量 (seq) 创建dict 。从dict 的输出中,我们可以看到键存在于字典中,但值被设置为none

dict.has_key() 方法

has_keys() 方法检查一个键是否存在于传递给它的字典中。你也可以用它来简单地验证一个键是否存在于字典中。然后它返回一个布尔值(TrueFalse)。

在这里,我们可以声明一个变量 (dict) 并使用 has_key 方法检查其中的键AgeSex 是否存在。

# declare the dictionary
dict = {'Name': 'Andrew', 'Age': 13}

# check for key in the dictionary
print("Value : %s" %  dict.has_key('Age'))
print("Value : %s" %  dict.has_key('Sex'))

#Output

# Value : True
# Value : False

当检查第一个键时,Age 返回true ,这意味着该项目存在于字典中。当检查第二个键时,Sex 返回false ,意思是这个项目不存在于字典中。

dict.items() 方法

items() 方法得到一个以元组对排列的 dictionary 的键和值的列表。我们可以用它来得到你的 dictionary 中所有项目的键和值的列表。

我们可以通过创建一个 dictionary (dict) 并使用items 方法将其中所有项目的键和值并排打印在一个列表中。

# declare the dictionary
dict = {'Name': 'Molly', 'Age': 7}

# get items in the dictionary
print("Value : %s" %  dict.items())

# output
# Value : [('Age', 7), ('Name', 'Molly')]

dict.keys() 方法

keys() 方法返回一个字典中所有现有键的列表。你可以用它来获得一个字典中所有键的列表,以执行你想要的任何进一步操作。

dict = {'Name': 'Andrew', 'Age': 23}
print("Value : %s" %  dict.keys())

#output
# Value : ['Age', 'Name']

Thedict.update(dict2) 方法

如果值不存在,update() 方法将一个 dictionary 的项插入另一个 dictionary 中。否则,它在适当的地方更新这些值。

你可以用update 方法来替代append 函数。然而,update 方法可以使用另一个 dictionary 来更新一个 dictionary 中的项目。

# declare the dictionaries
dict = {'Name': 'Molly', 'Age': 7}
dict2 = {'Sex': 'female' }

# update dict with dict2 items
dict.update(dict2)

print("Value : %s" %  dict)

# output
# Value : {'Name': 'Molly', 'Age': 7, 'Sex': 'female'}

通过创建两个字典,dictdict2 ,我们可以使用update 方法用dict2 的值来更新dict 的值。输出显示,dict 现在包含了dict2 的项目,这意味着在运行update 方法之前,它并不存在于dict 中。

dict.values() 方法

values() 方法返回一个存在于字典中的值的列表,但不包括它们的键。你可以用这个方法只得到你的 dictionary 中的值,而不用担心用它们的 key 来访问它们。

# declare dictionary
dict = {'Name': 'Zubair', 'Age': 7}

# get all item values
print("Value : %s" %  dict.values())

# output
# Value : [7, 'Zubair']

结论

通过这篇文章,我们学习了如何在 Python 中声明一个 dictionary,管理它的数据,并对它执行一些操作。此外,我们还了解了嵌套字典以及它们是如何工作的。

我希望这篇文章能帮助你成为一个更好的 Python 开发者。编码愉快

The postIntro to Python dictionariesappeared first onLogRocket Blog.