【问题标题】:How to split a dictionary of lists with arbitrary number of values into a list of dictionaries?如何将具有任意数量值的列表字典拆分为字典列表?
【发布时间】:2019-12-17 07:16:22
【问题描述】:

我正在尝试将列表字典拆分为字典列表。

我已尝试遵循示例 herehere_2。 Here_2 适用于 python 2.x,似乎不适用于 python 3.x

这里的第一个链接示例几乎可以正常工作,只是我只将第一个字典键值对作为 1 个列表返回。

使用 zip() 将列表字典转换为字典列表

test_dict = { "Rash" : [1], "Manjeet" : [1], "Akash" : [3, 4] } 
res = [dict(zip(test_dict, i)) for i in zip(*test_dict.values())] 
print ("The converted list of dictionaries " +  str(res)) 

Out: The converted list of dictionaries [{‘Rash’: 1, ‘Akash’: 3, ‘Manjeet’: 1}] 

DESIRED Out: The converted list of dictionaries [{‘Rash’: 1, ‘Akash’: 3, ‘Manjeet’: 1}, {‘Akash’: 4}]

【问题讨论】:

  • 除了这些例子,你还尝试过什么?可以理解的是,您可能不会找到适合您特定用例的东西。此外,您似乎正在尝试按索引对它们进行分组,因此对于第二个索引,您需要第二个字典
  • 上面的例子是我得到的最接近所需答案的例子。是的,我正在尝试按它们的键对值进行分组。键也没有相等数量的值。
  • 运行你的例子我得到输出The converted list of dictionaries [{'Rash': 1, 'Manjeet': 1, 'Akash': 3}, {'Rash': 3, 'Manjeet': 4, 'Akash': 4}]
  • 我已经编辑了 test_dict 和输出来澄清我的问题。

标签: python python-3.x list dictionary


【解决方案1】:

这是一个缓慢而脆弱的解决方案,没有花里胡哨(通常命名不好):

def dictlist_to_listdict(dictlist):
    output = []
    for k, v in dictlist.items():
        for i, sv in enumerate(v):
            if i >= len(output):
                output.append({k: sv})
            else:
                output[i].update({k: sv})
    return output


if __name__ == "__main__":
    test_dict = {"Rash": [1], "Manjeet": [1], "Akash": [3, 4]} 
    print(dictlist_to_listdict(test_dict))

【讨论】:

    【解决方案2】:

    当我使用 Python 3 在笔记本上运行您的代码时,它会打印您作为所需输出放置的行。 Perharps 我不太明白这个问题

    【讨论】:

    • 我已经编辑了 test_dict 和输出来澄清我的问题。
    猜你喜欢
    • 2010-12-19
    • 2011-05-04
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    相关资源
    最近更新 更多