循环列表并根据索引创建字典

时间:2018-10-25 09:50:24

标签: python

我想创建一个字典以获取如下输出:

代码:

d = {}
a = [[["man", "eater", "king"], ["king", "kong", "yes"]]]

for i, x in enumerate(a):
    for ii, xx in enumerate(x):
#this part i hope to check both the i and ii combination already inside the dictionary or not
#Example like if i or ii in d: # maybe something relevant
        d[i] = {ii:xx}
print(d)

当前输出:

{0: {1: ['king', 'kong', 'yes']}}

预期输出:

{{0: {0: ['man', 'eater', 'king']}},{0: {1: ['king', 'kong', 'yes']}}}

2 个答案:

答案 0 :(得分:2)

我想你是说这个意思

d = {i: {j: s for j, s in enumerate(l)} for i, l in enumerate(a)}

或带有嵌套for循环:

d = {}
for i, l in enumerate(a):
    t = {}
    for j, s in enumerate(l):
        t[j] = s
    d[i] = t

d变为:

{0: {0: ['man', 'eater', 'king'], 1: ['king', 'kong', 'yes']}}

请注意,您的预期输出不正确,因为它是一组dict,因为dict无法散列,所以不会发生。

答案 1 :(得分:1)

使用-k

例如:

collections.defaultdict

from collections import defaultdict

d = defaultdict(dict)
a = [[["man", "eater", "king"], ["king", "kong", "yes"]]]

for i, x in enumerate(a):
    for ii, xx in enumerate(x):
        d[i][ii] = xx
print(d)

d = {}
a = [[["man", "eater", "king"], ["king", "kong", "yes"]]]

for i, x in enumerate(a):
    d[i] = {}
    for ii, xx in enumerate(x):
        d[i][ii] = xx
print(d)

输出:

for i, x in enumerate(a):
    for ii, xx in enumerate(x):
        d.setdefault(i, {})[ii] = xx
print(d)