合并两个字典的最佳方式是合并第一个字典的值和第二个字典的键



我有两个字典:

a = {"foo":["bar","baz"]}
b = {"bar":[1,2],"baz":[9,10]}

我想合并它们,以便a的值中的每个元素("bar""baz")被b中的值替换,其中"bar""baz"是键。

所需输出:

{'foo': [[1, 2], [9, 10]]}

这是我目前如何实现合并:

for i,el in enumerate(a["foo"]):
    a["foo"][i] = b[el]
print a 
# {'foo': [[1, 2], [9, 10]]}

有更好的方法吗?

Also:不确定在同一篇文章中问这个是否合适,但我也想学习一种用pyspark做到这一点的方法。

您可以简单地使用列表推导式:

a['foo'] = [b[el] for el in a['foo']]

简单高效的martinjn Pieters…

我们有一个初学者,所以我将提请注意可变集合。

如果在下面的代码中修改了b中的列表,则a也将被修改。

a = {"foo": ["bar", "baz"]}
b = {"bar": [1, 2], "baz": [9, 10]}
a['foo'] = [b[el] for el in a['foo']]
expected = {'foo': [[1, 2], [9, 10]]}
assert a == expected

的例子:

b["bar"][0] = 789
print(a)
assert a == expected  # AssertionError

:

{'foo': [[789, 2], [9, 10]]}

为了避免这种情况,可以使用list()构造函数或[:]语法复制列表:

a['foo'] = [list(b[el]) for el in a['foo']]
# or: a['foo'] = [b[el][:] for el in a['foo']]
expected = {'foo': [[1, 2], [9, 10]]}
assert a == expected
b["bar"][0] = 789
print(a)
assert a == expected  # OK

如果你真的很偏执,你可以使用copy.deepcopy:

import copy
a['foo'] = [copy.deepcopy(b[el]) for el in a['foo']]
expected = {'foo': [[1, 2], [9, 10]]}
assert a == expected
b["bar"][0] = 789
print(a)
assert a == expected  # OK

最新更新