如何将包含任意数量值的列表的字典拆分为字典列表?

2024-10-06 08:48:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试着把一个列表词典拆分成一个列表词典。你知道吗

我试着遵循示例herehere_2。这里的\u2是用于python2.x的,似乎不适用于python3.x

这里的第一个链接示例几乎可以正常工作,只是我只将第一个dictionary键值对作为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}]

Tags: ofthetest示例列表herezipdict
2条回答

下面是一个缓慢而脆弱的解决方案,没有任何提示(通常是不好的命名):

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))

当我用python3在笔记本上运行您的代码时,它会打印您输入的行作为所需的输出。我对这个问题还不够理解

相关问题 更多 >