按多个值和其中一个键拆分字典

Splitting dict by multi values and one of the keys

我有一个多值字典和唯一键,我需要每个值都有一个键

data = {
    "id": [123,456,546,311], 
    "info": ["info1","info2","info3"],       
    .
    .
    .
}

需要这个答案:

data = {
    "id": [123], 
    "id": [456], 
    "id": [546],
    "id": [311]
    "info":["info1"],
    "info":["info2"],
    "info":["info3"]       

}

提前致谢

您不能在字典中多次使用相同的键(您将如何通过键访问它?)。

您可以改为提取元组列表,如下所示:

exploded = [(key, value) for key, values in data.items() for value in values]

输出:

[('id', 123), ('id', 456), ('id', 546), ('id', 311), 
 ('info', 'info1'), ('info', 'info2'), ('info', 'info3')]

正如 Olvin Roght 在评论中所说,据我所知,字典中不可能有非唯一键。在官方Python文档中是这样写的:

"It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary)."

(来源:https://docs.python.org/3/tutorial/datastructures.html