Python 向字典添加元素
高级、多用途的Python是一种非常受欢迎的编程语言。Python被用于先进的软件开发项目,如Web开发和机器学习应用。
在本文中,我们将学习向字典添加元素的各种方法。
你从Python中的字典中理解什么
Python中的字典存储键值对,而不像其他数据类型只包含一个单一值作为元素。它用于存储类似于映射的数据值。字典包含键值对以使其更高效。
在字典中,每个键值对由冒号分隔;相反,每个键由逗号分隔。字典的键值可以重复,可以是任何类型,但键值必须是唯一且不可变的数据类型,例如字符串、整数和元组。
语法
Key:value
首先让我们学习如何创建一个字典 –
我们可以通过不同的方式创建字典,比如函数式方法,首先创建字典类,然后定义init函数。正如我们所知,字典包含键值对,接下来我们将编写函数来添加键值对,最后是主函数。
但是在这里我们将创建一个简单的字典。
示例
以下示例展示了如何在Python中创建一个字典。
# Let's create a dictionary here
create_dictionary = {'Name': 'Devang', 'Age': 24, 'Quality': 'Hardworking'}
print(create_dictionary)
输出
{'Name': 'Devang', 'Age': 24, 'Quality': 'Hardworking'}
到目前为止,我们已经搞清楚了基础知识。现在让我们将这些基础知识应用于在字典中添加元素。有多种方法可以实现相同的功能,但在这里我们将了解四种最简单和最重要的方法。
使用update()方法
这个方法用于从可迭代的键值对或不同字典对象的元素中更新字典。这个方法很适用,因为当我们需要添加很多键/值对时,它可以很容易地完成任务。
语法
dict.update([other])
示例
在下面的程序中,创建了一个名为dict的字典,其中包含两个键值对。然后,程序打印出字典的初始版本。下一行将另一个键值对添加到字典中并进行更新。之后,创建了一个名为’dictionary_A’的新字典,其中包含两个键值对,然后使用.update()方法将其添加到dict中,并在最后一步打印出来。
dict = {'1': 'An', '2': 'Apple a day'}
print( "First Dictionary is as following :", dict)
# for adding the key3 that is an another key
dict.update({'3': 'keeps doctor'})
print( "Updated version of Dictionary is as following : ", dict)
# for adding from dictionary_A (key4 and key5) to dict
dictionary_A = {'4': 'is', '5': 'away'}
dict.update(dictionary_A)
print(dict)
输出
First Dictionary is as following : {'1': 'An', '2': 'Apple a day'}
Updated version of Dictionary is as following : {'1': 'An', '2': 'Apple a day', '3': 'keeps doctor'}
{'1': 'An', '2': 'Apple a day', '3': 'keeps doctor', '4': 'is', '5': 'away'}
使用for循环和enumerate()方法
Python提供了一个内置函数 enumerate() 方法。它的工作方式是将计数器添加到可迭代对象中,并以枚举对象的形式返回。
步骤
首先创建一个元素列表,然后使用enumerate()方法对列表进行迭代。接下来,通过使用索引作为每个值的键,将每个元素添加到字典中。
示例
程序中创建了一个字典和一个列表。然后,for循环遍历第二个列表中的每个项,并将其分配给第一个列表中以其对应的索引作为键值的键。打印语句打印出在for循环修改后的firstlist的最终版本。
firstlist = {"Apple": 1, "Boy": 2, "Cat": 3}
secondlist = ["first: 1", "second:2", "third:3"]
for i, val in enumerate(secondlist):
firstlist[i] = val
print(firstlist)
输出
{'Apple': 1, 'Boy': 2, 'Cat': 3, 0 : 'first : 1', 1 : 'second : 2', 2 : 'third : 3'}
使用Zip方法
在使用容器或可迭代对象时,Python中的zip()函数创建一个包含来自每个容器映射值的单个迭代器对象。它用于映射几个容器的共享索引,以便单个实体可以访问它们所有。现有的字典可以用字典{}代替。
示例
以下程序创建了一个带有三个键(1、2、3)和值(”Ship”、”for”、”sale”)的字典,然后打印出结果字典。
dictionary = {}
keys_num = ['1', '2', '3']
values_first = ['Ship', 'for', 'sale']
for keys_num, value_first in zip(keys_num, values_first):
dictionary[keys_num] = value_first
print(dictionary)
输出
{‘1’: ‘Ship’, ‘2’: ‘for’, ‘3’: ‘sale’}
通过使用“in”操作符和if语句
在这个方法中,我们使用了 ** if** 语句,它检查字典中是否已经存在该键。如果键不存在,则将其添加到字典中;如果已经存在,则输出键已经存在于字典中的消息。
示例
下面的程序创建了一个名为”firstdictionary”的字典,其中包含键”apple”、”boy”和”cat”。然后,它检查字典中是否存在键”dog”。如果不存在,则将键值对(“dog”: 4)添加到字典中。否则,打印一条消息,表明该键已经存在于字典中,并且不会覆盖其值。最后,打印出firstdictionary的所有内容。
firstdictionary = {"apple": 1, "boy": 2, "cat": 3}
if "dog" not in firstdictionary:
firstdictionary["dog"] = "4"
else:
print("Key is already present in the dictionary : One. Hence value is not overwritten ")
print(firstdictionary)
输出
{'apple': 1, 'boy': 2, 'cat': 3, 'dog': '4'}
示例
在这里,我们使用例子创建了一个差异,如果键不存在,则显示case1,否则显示case2。
firstdictionary = {"apple": 1, "boy": 2, "cat": 3, "dog": 4}
if "dog" not in firstdictionary:
firstdictionary["dog"] = "4"
else:
print("Key is already present in the dictionary : One. Hence value is not overwritten ")
print(firstdictionary)
输出
Key is already present in the dictionary : One. Hence value is not overwritten {'apple': 1, 'boy': 2, 'cat': 3, 'dog': 4}
使用 **
运算符
在这种方法中,我们可以使用 ** 运算符直接将旧字典和新字典的键/值对合并在一起。因此,**
运算符的作用是将键/值对解包到新字典对象中。
步骤
创建一个字典,然后创建另一个要合并到原始字典中的字典。然后在键/值对前面应用 ** 运算符。
示例
还有一种方法setitem来将元素添加到字典中,但这种方法的计算效率较低,因此我们通常不使用这种方法。
firstdictionary = {'apple': 1, 'boy': 2}
new_dictionary = {**firstdictionary, **{'cat': 3}}
print(firstdictionary)
print(new_dictionary)
结果
{'apple': 1, 'boy': 2}
{'apple': 1, 'boy': 2, 'cat': 3}
结论
在这篇文章中,我们解释了五种不同的方法,展示了五种不同的方法来使用Python向字典中添加元素。