首页 > 解决方案 > 列表格式的嵌套字典

问题描述

我有 3 个列表 - name1、name2、distance - 使用以下代码:

distdictionary = [{a: {b:c}} for a,b,c in zip(name1, name2, distance)]

我得到一个看起来像这样的字典:

[{'name1': {'name2': 737}},{'name1': {'name2': 717}}, {'name1': {'name2': 749}}....etc]

我正在寻找的是:

{'name1':{'name2': 737,'name2': 717, 'name2': 749}....etc]

name1 与 name2 和距离具有一对多的关系,并且将是嵌套字典的开始。

添加一些显示列表的说明/编辑:

name1    name2    distance  
-----    -----    --------   
John     Sarah    23  
John     Jane     64  
John     Anne     45  
David    Sarah    33  
David    Jane     56  
David    Anne     67  
Mike     Sarah    87  
Mike     Jane     24  
Mike     Anne     89  

嵌套字典应如下所示:

{'John: {'Sarah': 23, 'Jane': 64, 'Anne': 45}, 
David: {'Sarah': 33, 'Jane': 56, 'Anne': 67},
Mike: {'Sarah': 87, 'Jane': 24, 'Anne': 89}}  

非常感谢您对此的帮助....

标签: pythonlistdictionarynested

解决方案


您可以通过创建一个嵌套循环来解决这个问题,并在其中有一个临时字典,该字典会针对name1.

temp_dict1在下面找到示例,每个temp_dict2temp_dict3仅由您应该创建的循环中的一个临时字典表示。解释:

name1 =["John","John","John","David","David","David","Mike","Mike","Mike"]
name2 = ["Sarah","Jane","Anne","Sarah","Jane","Anne","Sarah","Jane","Anne"]
distance =[23,64,45,33,56,67,87,24,89]
temp_dict1 = {}
temp_dict2 = {}
temp_dict3 = {}
my_dict={}

temp_dict1[name2[0]]=distance[0]
temp_dict1[name2[1]]=distance[1]
temp_dict1[name2[2]]=distance[2]
my_dict[name1[0]]=temp_dict1

temp_dict2[name2[3]]=distance[3]
temp_dict2[name2[4]]=distance[4]
temp_dict2[name2[5]]=distance[5]
my_dict[name1[3]]=temp_dict2

temp_dict3[name2[6]]=distance[6]
temp_dict3[name2[7]]=distance[7]
temp_dict3[name2[8]]=distance[8]
my_dict[name1[6]]=temp_dict3



my_dict

输出是:

{'John': {'Sarah': 23, 'Jane': 64, 'Anne': 45},
 'David': {'Sarah': 33, 'Jane': 56, 'Anne': 67},
 'Mike': {'Sarah': 87, 'Jane': 24, 'Anne': 89}}

最终解决方案是:

name1 =["John","John","John","David","David","David","Mike","Mike","Mike"]
name2 = ["Sarah","Jane","Anne","Sarah","Jane","Anne","Sarah","Jane","Anne"]
distance =[23,64,45,33,56,67,87,24,89]
my_dict={}
start = 0
stop = 3
while start < len(name1):
    temp_dict = {}
    for i in range(start,stop):
        temp_dict[name2[i]]=distance[i]
        my_dict[name1[start]]=temp_dict
    start = start + 3
    stop = stop +3

推荐阅读