使用多个列表创建复杂的字典 [英] Create a complex dictionary using multiple lists

查看:91
本文介绍了使用多个列表创建复杂的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有三个列表,并且想使用列表中的项作为键和值来创建字典.我希望它看起来像这样:

Lets say I have three lists and want to create a dictionary using items from the lists as keys and values. I want it to look like this:

main_dic = {'FL-01':{'existing': 22, 'proposed': 47}, 'FL-01P': {'existing': 5, 'proposed': 8}, 'P04A': {'existing': 14, 'proposed': 38}, 'P05': {'existing': 7, 'proposed': 95}}

所以,这是我的三个列表:

So, here are my three lists:

units = ['FL-01','FL-01P','P04A','P05']
existing = [22,5,14,7]
proposed = [47, 8, 38, 95]

我首先设置并清空字典

 main_dic = dict()

现在我很困惑,因为我需要他们保持秩序.我想我可以将现有的和建议的文件压缩在一起,但这只是一个简单的示例,如果我添加了第四个列表,例如future = [4, 7, 91, 26],那将不起作用.我想首先迭代扔出的单位列表,因为它们将是主要字典的关键,并以某种方式使用setdefault(k, v),但是我不确定如何正确地应用它.有什么建议?

Now is where I get confused, because I need them to stay in order. I guess I could zip the existing and proposed together, but this is just a simple example and if I added a fourth list, say future = [4, 7, 91, 26], then that would not work. I want to iterate threw the units list first since they will be the key to the primary dictionary and use setdefault(k, v) somehow but I am not sure how to correctly apply this. Any suggestions?

推荐答案

您正确使用了zip:

units = ['FL-01','FL-01P','P04A','P05']
existing = [22,5,14,7]
proposed = [47, 8, 38, 95]

d = {u: {'existing': e, 'proposed': p} for u, e, p in zip(units, existing, proposed)}

print(d)
# {'FL-01': {'existing': 22, 'proposed': 47},
#  'FL-01P': {'existing': 5, 'proposed': 8},
#  'P04A': {'existing': 14, 'proposed': 38},
#  'P05': {'existing': 7, 'proposed': 95}}

这篇关于使用多个列表创建复杂的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆