Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary of lists to nested dictionary

I have the following dictionary {44: [0, 1, 0, 3, 6]} and need to convert this to dict1 = {44: {0:0, 1:1, 2:0, 3:3, 4:6}} but my current for loop doesn't work:

maxnumbers = 5          #this is how many values are within the list
for i in list(range(maxnumbers)):
    for k in list(dict1.keys()):
        for g in dict1[k]:
            newdict[i] = g
print(num4)

Can you help me? Thanks in advance.

like image 272
I need programming help Avatar asked Jun 03 '19 14:06

I need programming help


3 Answers

You can use a dictionary comprehension with enumerate:

d = {44: [0, 1, 0, 3, 6]}

{k:dict(enumerate(v)) for k,v in d.items()}
# {44: {0: 0, 1: 1, 2: 0, 3: 3, 4: 6}}
like image 197
yatu Avatar answered Oct 23 '22 13:10

yatu


Use a simple nested dictionary-comprehension that uses enumerate:

d = {44: [0, 1, 0, 3, 6]}

print({k: {i: x for i, x in enumerate(v)} for k, v in d.items()})
# {44: {0: 0, 1: 1, 2: 0, 3: 3, 4: 6}}
like image 5
Austin Avatar answered Oct 23 '22 13:10

Austin


a = {44: [0, 1, 0, 3, 6]}
a= {i:{j:a[i][j] for i in a for j in range(len(a[i]))}}

print(a)

output

 {44: {0: 0, 1: 1, 2: 0, 3: 3, 4: 6}}
like image 2
sahasrara62 Avatar answered Oct 23 '22 14:10

sahasrara62