Beginner
Beginner

Reputation: 147

Looping a list and create dictionary based on the index

I would like to create a dictionary to get the output as follow:

Code:

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)

Current output:

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

Expected output:

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

Upvotes: 2

Views: 44

Answers (2)

blhsing
blhsing

Reputation: 106768

I think you mean this:

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

or with nested for loops:

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

d becomes:

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

Note that your expected output is incorrect because it is a set of dicts, which can't happen since dicts are unhashable.

Upvotes: 2

Rakesh
Rakesh

Reputation: 82765

Use collections.defaultdict

Ex:

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)

or

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)

or

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

Output:

defaultdict(<type 'dict'>, {0: {0: ['man', 'eater', 'king'], 1: ['king', 'kong', 'yes']}})

Upvotes: 1

Related Questions