Python字典追加
时间:2020-02-23 14:42:38 来源:igfitidea点击:
在本教程中,我们将看到如何将项目添加到字典中。
在Python中没有名为添加的方法,我们可以实际使用更新方法将键值对添加到字典中。
将项目添加到字典中的最简单方法
dict1={1:"one",2:"two",3:"three"}
print(dict1)
#append key value pair to dict
dict1[4]="four"
print(dict1)
输出:
{1: 'one', 2: 'two', 3: 'three'}
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
我们可以使用Dictionary的Update方法将字典或者Itabreation进行追加。
dict1={1:"one",2:"two",3:"three"}
print(dict1)
#you can add another dictionary to current dictionary by using update method
dict2={4:"four",5:"five",6:"six"}
dict1.update(dict2)
print(dict1)
#You can add iterable too using update method as below
dict1.update(a=1, b=2, c=3)
print(dict1)
输出:
{1: 'one', 2: 'two', 3: 'three'}
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six'}
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 'a': 1, 'b': 2, 'c': 3}

