python - 列表格式的嵌套字典
问题描述
我有 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}}
非常感谢您对此的帮助....
解决方案
您可以通过创建一个嵌套循环来解决这个问题,并在其中有一个临时字典,该字典会针对name1
.
temp_dict1
在下面找到示例,每个temp_dict2
和temp_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
推荐阅读
- wordpress - the_posts_pagination 在 wordpress 主页中不起作用
- hibernate - 使用 jpa 保存实体时出现“org.hibernate.TransientObjectException:代理未与会话关联”错误
- android - 如何不在 CalendarView 中设置默认日期?
- php - 如果它与字符串匹配,则从数组中删除值 - php
- angular - Angular 7:CustomMaterialModule 在 FeatureLazyLoadedModule 中不起作用
- php - 未定义变量:form_data (Laravel 5.7)
- javascript - 如何从这里获取 ajax url 成功函数值以全局使用 -> $('.demo').html(html);
- c# - C#中带参数的属性
- azure - 如何使用工作流在 Azure 上设计微服务系统以按顺序调用它们
- javascript - 通过 Web (javascript) 或独立 (Java) 将 ARCore Android 与桌面连接