更新 Python 中的一系列词典
Updating a sequence of Dictionaries in Python
我遇到了一个需要用dict.update()
解决问题的练习。
Body of the task: The dict.update method merges two dicts. Write a
function that takes any number of dicts and returns a dict that
reflects the combination of all of them. If the same key appears in
more than one dict, then the most recently merged dict’s value should
appear in the output.
我设法为 2 个输入编写了代码:
def d_update(first, second):
first = first.update(second)
return d1
d1 = {'a': 1, 'b': 2, 'c': 3}
d2 = {'a': 1, 'b': 2, 'c': 5}
print(d_update(d1,d2)) #outout is {'a': 1, 'b': 2, 'c': 5}
但我正在努力安排多个指令序列。尝试使用:
def d_update(*sequence):
for D in sequence:
D = D.update(D)
return D
但是 returns None
.
我该怎么办?
您的代码完全正确。你只是犯了一个小错误。
.update
是一个就地函数。它 returns None
或什么都没有。
通过 D=D.update(D)
,您将 None
分配给 D
只需D.update(D)
这是更新后的代码。
def d_update(*sequence):
for D in sequence:
D.update(D)
return D
d1 = {'a': 1, 'b': 2, 'c': 3}
d2 = {'a': 1, 'b': 2, 'c': 5}
print(d_update(d1,d2)) #outout is {'a': 1, 'b': 2, 'c': 5}
我遇到了一个需要用dict.update()
解决问题的练习。
Body of the task: The dict.update method merges two dicts. Write a function that takes any number of dicts and returns a dict that reflects the combination of all of them. If the same key appears in more than one dict, then the most recently merged dict’s value should appear in the output.
我设法为 2 个输入编写了代码:
def d_update(first, second):
first = first.update(second)
return d1
d1 = {'a': 1, 'b': 2, 'c': 3}
d2 = {'a': 1, 'b': 2, 'c': 5}
print(d_update(d1,d2)) #outout is {'a': 1, 'b': 2, 'c': 5}
但我正在努力安排多个指令序列。尝试使用:
def d_update(*sequence):
for D in sequence:
D = D.update(D)
return D
但是 returns None
.
我该怎么办?
您的代码完全正确。你只是犯了一个小错误。
.update
是一个就地函数。它 returns None
或什么都没有。
通过 D=D.update(D)
,您将 None
分配给 D
只需D.update(D)
这是更新后的代码。
def d_update(*sequence):
for D in sequence:
D.update(D)
return D
d1 = {'a': 1, 'b': 2, 'c': 3}
d2 = {'a': 1, 'b': 2, 'c': 5}
print(d_update(d1,d2)) #outout is {'a': 1, 'b': 2, 'c': 5}