【问题标题】:Python combine 2 nested dictionary with multiple values for one keyPython将2个嵌套字典与一个键的多个值组合在一起
【发布时间】:2018-07-11 11:51:00
【问题描述】:

我有 2 个默认 dict.. 我想将这 2 个结合起来。 请帮帮我。

{ Fun :{ 1:hi , 2: hello} , fun2 : {3: bye, 4: good bye}}
  {Fun :{ 1:abc , 2: xyZ} , fun2 : {3: qpr, 4: jkl}}

我想将这些组合起来,在键 1 下得到 'hi' 和 'abc' 以及 'fun'

【问题讨论】:

  • "'hi' and 'abc' " - 连接在一起还是作为一个列表?还是别的什么?
  • 在python中,字典键是唯一的。这意味着您只能在同一个字典中使用一个“Fun”。
  • 标准库中没有这种东西。不过,您可以使用 defaultdict(docs.python.org/3.1/library/…)。示例代码:- >>> from collections import defaultdict >>> md = defaultdict(list) >>> md[1].append('a') >>> md[1].append('b') >> > md[2].append('c') >>> md[1] // 输出为 ['a', 'b'] >>> md[2] // 输出为 ['c']

标签: python dictionary


【解决方案1】:

字典键是唯一的。您不能将两个值附加到一个键上。

但是,您可以构建一个嵌套字典,其中包含将键映射到值列表的子字典。为此,您可以使用collections.defaultdict

d1 = {'Fun': {1: 'hi', 2: 'hello'}, 'fun2': {3: 'bye', 4: 'good bye'}}
d2 = {'Fun': {1: 'abc', 2: 'xyZ'}, 'fun2': {3: 'qpr', 4: 'jkl'}}

from collections import defaultdict

dd = defaultdict(lambda: defaultdict(list))

for top_dict in (d1, d2):
    for k1, v1 in top_dict.items():
        for k2, v2 in v1.items():
            dd[k1][k2].append(v2)

print(dd)

defaultdict({'Fun': defaultdict(list,  {1: ['hi', 'abc'], 2: ['hello', 'xyZ']}),
             'fun2': defaultdict(list, {3: ['bye', 'qpr'], 4: ['good bye', 'jkl']})})

【讨论】:

    猜你喜欢
    • 2020-07-29
    • 2012-02-10
    • 2011-07-31
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 2019-04-06
    • 2019-01-09
    • 1970-01-01
    相关资源
    最近更新 更多