【问题标题】:Convert a dictionary of dictionaries to dictionary of lists将字典字典转换为列表字典
【发布时间】:2017-09-26 09:08:02
【问题描述】:

我有一本字典:

d = {"a": {"x":1, "y":2, "z":3}, "b": {"x":2, "y":3, "z":4}, "c": {"x":3, "y":4, "z":5}}

我想把它转换成:

new_d = {"x":[1, 2, 3], "y": [2, 3, 4], "z": [3, 4, 5]}

要求new_d[key][i]new_d[another_key][i]应该在d的同一个子字典中。

所以我创建了new_d = {},然后:

for key in d.values()[0].keys():
    new_d[key] = [d.values()[i][key] for i in range(len(d.values()))]

这给了我我的预期,但我只是想知道是否有一些用于此操作的内置函数或者有更好的方法来执行此操作。

【问题讨论】:

    标签: python python-2.7 dictionary


    【解决方案1】:

    这个操作没有内置函数,没有。我只是循环遍历values 直接

    new_d = {}
    for sub in d.itervalues():              # Python 3: use d.values()
        for key, value in sub.iteritems():  # Python 3: use d.items()
            new_d.setdefault(key, []).append(value)
    

    这避免了每次为dict.values() 调用创建一个新列表。

    请注意,字典没有顺序。但是,结果列表中的值将符合您的标准;它们将以相同的顺序添加到new_d 中的每个键:

    >>> d = {"a": {"x":1, "y":2, "z":3}, "b": {"x":2, "y":3, "z":4}, "c": {"x":3, "y":4, "z":5}}
    >>> new_d = {}
    >>> for sub in d.values():
    ...     for key, value in sub.items():
    ...         new_d.setdefault(key, []).append(value)
    ...
    >>> new_d
    {'x': [1, 2, 3], 'y': [2, 3, 4], 'z': [3, 4, 5]}
    

    【讨论】:

      【解决方案2】:

      列表理解方法

      如果您喜欢字典和列表推导式...

      d1 = {"a": {"x": 1, "y": 2, "z": 3},
            "b": {"x": 2, "y": 3, "z": 4},
            "c": {"x": 3, "y": 4, "z": 5}}
      
      dl1 = {kl: [v for di in d1.values() for k, v in di.items() if k == kl]
             for di in d1.values() for kl in di.keys()}
      
      print(dl1)
      

      并产生预期的结果......

      {'x': [1, 2, 3], 'y': [2, 3, 4], 'z': [3, 4, 5]}
      

      【讨论】: