我有 4 个 python 字典,其中每个键的值是另一个字典:
a={'a': {'e': 4}}
b={'b': {'f': 5}}
c={'c': {'g': 6}}
d={'d': {'h': 7}}
Run Code Online (Sandbox Code Playgroud)
我想将字典 a、b、c 和 d 合并在一起,这样我就有了一个最终的字典,如下所示:
{'a': {'e': 4}, 'b': {'f': 5}, 'c': {'g': 6}, 'd': {'h': 7}}
Run Code Online (Sandbox Code Playgroud)
其中父字典的顺序是我添加每个原始字典的顺序。
所以我创建了一个空字典并执行了以下操作:
x={} #create empty dictionary
x.update(a) #update with first dictionary
print x
x.update(b) #update with second dictionary
print x
x.update(c) #update with third dictionary
print x
x.update(d) #update with forth dictionary
print x
Run Code Online (Sandbox Code Playgroud)
结果是这样的:
{'a': {'e': 4}}
{'a': {'e': 4}, 'b': {'f': 5}}
{'a': {'e': 4}, 'c': {'g': 6}, 'b': {'f': 5}}
{'a': {'e': 4}, 'c': {'g': 6}, 'b': {'f': 5}, 'd': {'h': 7}}
Run Code Online (Sandbox Code Playgroud)
我不知道为什么在第三次更新后,c 被添加到 a 和 b 之间的 x。然后在第四次更新之后, d 以某种方式在最后添加。似乎是随机的。
请记住,排序将不起作用。以上是我想要的一个例子,我的键可能并不总是按字母顺序排列。我只是想要我添加每个字典的顺序。
编辑:这是针对 python 2.7,但感谢 3.6 的答案,因为我将在不久的将来将工具从 2 迁移到 3。
您可以将每个 dict 解包为一个(在 python3.6+ 中,它将保留插入顺序):
>>> {**a, **b, **c, **c, **d}
{'a': {'e': 4}, 'b': {'f': 5}, 'c': {'g': 6}, 'd': {'h': 7}}
Run Code Online (Sandbox Code Playgroud)
在 python 3.9+ 中,您可以使用合并运算符:
>>> a | b | c | d
{'a': {'e': 4}, 'b': {'f': 5}, 'c': {'g': 6}, 'd': {'h': 7}}
Run Code Online (Sandbox Code Playgroud)
编辑
这也适用于OrderedDicts。当您使用 python 2.7 时,这将保留顺序:
>>> from collections import OrderedDict
>>> OrderedDict(**a, **b, **c, **d)
OrderedDict([('a', {'e': 4}), ('b', {'f': 5}), ('c', {'g': 6}), ('d', {'h': 7})])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53 次 |
| 最近记录: |