chr09
chr09

Reputation: 21

How to flatten a nested list to a dictionary in python?

For example, say I have a nested list with the values

[['10', 'k', '19', 'p', '30'], ['11', 'f', '12', 'k', '15']]

And I want to create a nested dictionary with the format:

{
10: {'k': 19, 'p': 20},
11: {'f': 12,'k':  15}
}

The values are always in pairs (letter and number like k and 19)

How might I go about this? So far I've just used a simple function to create an empty dictionary and add all the keys but it seems to go on forever.

Upvotes: 0

Views: 132

Answers (2)

Joshua Varghese
Joshua Varghese

Reputation: 5202

Simpler Solution (from @Jon):

{int(k): {a: int(b) for a, b in zip(*[iter(v)]*2)} for k, *v in list1}

This keeps the integers all right.


Try:

{i[0]:{k:m for k,m in zip(i[1::2],i[2::2])} for i in list1 }

Here:

list1 = [[' 10', 'k', '19', 'p', '30'], [' 11', 'f', '12', 'k', '15']]

Gives:

{' 10': {'k': '19', 'p': '30'}, ' 11': {'f': '12', 'k': '15'}}

If you want them as int:

{int(i[0]):{k:int(m) for k,m in zip(i[1::2],i[2::2])} for i in list1 }

Gives:

{10: {'k': 19, 'p': 30}, 11: {'f': 12, 'k': 15}}

A solution for:

[['10', 'k', '19', 'p', '30'], ['11', 'f', '12', 'k', '15'], ['10', 'k', '20', 'm', '23']]

Is:

dic = {}
for i in list1:
    if int(i[0]) not in dic:
        dic[int(i[0])] = {k:int(m) for k,m in zip(i[1::2],i[2::2])}
    else:
        dic[int(i[0])].update({k:int(m) for k,m in zip(i[1::2],i[2::2])})

Upvotes: 4

ernest_k
ernest_k

Reputation: 45319

You can use this comprehension:

{k[0]:k[1] 
 for k in [(l[0], {l[m]:int(l[m+1]) for m in range(1, len(l), 2)}) 
           for l in list1] }

Which ouputs

{' 10': {'k': 19, 'p': 30}, ' 11': {'f': 12, 'k': 15}}

Upvotes: 3

Related Questions