热线电话:13121318867

登录
2019-02-18 阅读量: 811
python如何向字典添加元素

在Python Dictionary中,元素的添加可以通过多种方式完成。通过定义值和键,例如Dict [Key] ='Value',可以将一次一个值添加到Dictionary中。可以使用内置update()方法更新Dictionary中的现有值。嵌套键值也可以添加到现有词典中。

注意 -添加值时,如果键值已存在,则值会更新,否则会将具有该值的新键添加到词典中。

# Creating an empty Dictionary

Dict = {}

print("Empty Dictionary: ")

print(Dict)

# Adding elements one at a time

Dict[0] = 'Geeks'

Dict[2] = 'For'

Dict[3] = 1

print("\nDictionary after adding 3 elements: ")

print(Dict)

# Adding set of values

# to a single Key

Dict['Value_set'] = 2, 3, 4

print("\nDictionary after adding 3 elements: ")

print(Dict)

# Updating existing Key's Value

Dict[2] = 'Welcome'

print("\nUpdated key value: ")

print(Dict)

# Adding Nested Key value to Dictionary

Dict[5] = {'Nested' :{'1' : 'Life', '2' : 'Geeks'}}

print("\nAdding a Nested Key: ")

print(Dict)

输出:

Empty Dictionary: 
{}

Dictionary after adding 3 elements:
{0: 'Geeks', 2: 'For', 3: 1}

Dictionary after adding 3 elements:
{0: 'Geeks', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}

Updated key value:
{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}

Adding a Nested Key:
{0: 'Geeks', 2: 'Welcome', 3: 1, 5: {'Nested': {'1': 'Life', '2': 'Geeks'}}, 'Valu
0.0000
1
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子