将列表列表转换为字典词典(Python) [英] Converting list of lists of lists into dictionary of dictionaries (Python)

查看:1619
本文介绍了将列表列表转换为字典词典(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个列表X = [[[2, 2]], [[2, 5], [3, 1]], [[3, 3], [4, 4], [1, 6]], [[1, 1], [4, 0]], [[]]].我想将X转换成字典,像这样.

Suppose I have a list X = [[[2, 2]], [[2, 5], [3, 1]], [[3, 3], [4, 4], [1, 6]], [[1, 1], [4, 0]], [[]]]. I want to convert X into a dictionary of dictionaries like so.

G = {0: {2: 2},
     1: {2: 5, 3: 1},
     2: {3: 3, 4: 4, 1: 6},
     3: {1: 1, 4: 0},
     4: {}
    }

到目前为止,我已经拥有

So far I have

for i in range(0,len(X)):
    for j in range(0, len(X[i])):
        G[i] = {X[i][j][0]: X[i][j][1]}

产生

{0: {2: 2}}
{0: {2: 2}, 1: {2: 5}}
{0: {2: 2}, 1: {3: 1}}
{0: {2: 2}, 1: {3: 1}, 2: {3: 3}}
{0: {2: 2}, 1: {3: 1}, 2: {4: 4}}
{0: {2: 2}, 1: {3: 1}, 2: {1: 6}}
{0: {2: 2}, 1: {3: 1}, 2: {1: 6}, 3: {1: 1}}
{0: {2: 2}, 1: {3: 1}, 2: {1: 6}, 3: {4: 0}}
Traceback (most recent call last):
G[i] = {X[i][j][0]: X[i][j][1]}
IndexError: list index out of range

首先,它仅更新字典,而不附加新键;其次,我在空白列表中失败.
有什么建议吗?

First it only updates the dictionaries instead of appending new keys, second it fails me at my empty list.
Any suggestions?

推荐答案

如果您使用的是Python 2.7,则可以使用字典理解.

If you're using Python 2.7 you can use a dictionary comprehension.

X =  [[[2, 2]], [[2, 5], [3, 1]], [[3, 3], [4, 4], [1, 6]], [[1, 1], [4, 0]], [[]]]

d = {k: dict(v) if v[0] else {} for k, v in enumerate(X)}

有人给出了一个很好的答案,但是他们删除了该答案,他们还使用了字典理解功能,但是对空列表的处理更好(我认为).像这样

someone had a nice answer but they deleted it where they also used a dictionary comprehension but handled the empty lists better (I think). It went like so

d = {k: dict(item for item in v if item) for k, v in enumerate(X)}

这篇关于将列表列表转换为字典词典(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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