在python中更新字典 [英] Updating a dictionary in python
问题描述
我在这个问题上停留了很长时间,无法解决。我只想了解我所缺少的内容以及为什么需要它。
我需要做的是制作一个函数,将每个给定的键/值对添加到字典中。参数key_value_pairs将是形式为(键,值)的元组列表。
I've been stuck on this question for quite sometime and just can't figure it out. I just want to be able to understand what I'm missing and why it's needed. What I need to do is make a function which adds each given key/value pair to the dictionary. The argument key_value_pairs will be a list of tuples in the form (key, value).
def add_to_dict(d, key_value_pairs):
newinputs = [] #creates new list
for key, value in key_value_pairs:
d[key] = value #updates element of key with value
if key in key_value_pairs:
newinputs.append((d[key], value)) #adds d[key and value to list
return newinputs
我不知道给出了当d和key_value_pairs具有不同的键时如何更新值变量的方法。
I can't figure out how to update the "value" variable when d and key_value_pairs have different keys.
这些方案中的前三种有效,但其余方案都失败了
The first three of these scenarios work but the rest fail
>>> d = {}
>>> add_to_dict(d, [])
[]
>>> d
{}
>>> d = {}
>>> add_to_dict(d, [('a', 2])
[]
>>> d
{'a': 2}
>>> d = {'b': 4}
>>> add_to_dict(d, [('a', 2)])
[]
>>> d
{'a':2, 'b':4}
>>> d = {'a': 0}
>>> add_to_dict(d, [('a', 2)])
[('a', 0)]
>>> d
{'a':2}
>>> d = {'a', 0, 'b': 1}
>>> add_to_dict(d, [('a', 2), ('b': 4)])
[('a', 2), ('b': 1)]
>>> d
{'a': 2, 'b': 4}
>>> d = {'a': 0}
>>> add_to_dict(d, [('a', 1), ('a': 2)])
[('a', 0), ('a':1)]
>>> d
{'a': 2}
谢谢
已编辑。
推荐答案
Python内置了此功能:
Python has this feature built-in:
>>> d = {'b': 4}
>>> d.update({'a': 2})
>>> d
{'a': 2, 'b': 4}
或者如果您不被允许使用 dict.update
:
Or given you're not allowed to use dict.update
:
>>> d = dict(d.items() + {'a': 2}.items()) # doesn't work in python 3
这篇关于在python中更新字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!