如何用3个列表在Python中创建嵌套字典 [英] How to Create Nested Dictionary in Python with 3 lists

查看:375
本文介绍了如何用3个列表在Python中创建嵌套字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设,我已经创建了3个列表,并且我想为其创建字典.例如

Let us Suppose, I have created 3 lists and I want to create a dictionary for it. e.g.

a= ['A', 'B', 'C', 'D']
b =[1, 2, 3, 4]
c = [9, 8, 7, 6]

现在,我要创建一个像这样的字典:

Now What I want is to create a dictionary like this:

{'A':{'1' :'9'} , 'B':{'2':'8'}, 'C':{'3':'7'} , 'D':{'4':'6'}}

有可能,有人可以帮我吗?

is it possible, Can Someone Help me on this?

推荐答案

您可以从zip -ed列表中创建字典,并将int值转换为字符串-如果我理解您的问题正确的话

You can create the dictionary from zip-ed lists and convert the int values to strings - if I understood your question proper

dct = {x: {str(y): str(z)} for x, y, z in zip(a,b,c)}

输出:

{'A': {'1': '9'}, 'C': {'3': '7'}, 'B': {'2': '8'}, 'D': {'4': '6'}}

这篇关于如何用3个列表在Python中创建嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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