Andy2
Andy2

Reputation: 39

Converting Python Dictionary to List of lists

I have a dict:

d={10:[2,"str1",4] , 20:[5,"str2",7] , 30:[8,"str3",10]}

I need to make a list from this dict:

lst=[[10,2,"str1",4] , [20,5,"str2",7] ,[30,8,"str3",10]]

if I use lst= map(list, d.items())` the key is not in the same list like the values:

lst=[[10,[2,"str1",4]] , [20,[5,"str2",7]] ,[30,[8,"str3",10]]

I also tried this code:

for k,v in d.items():
    for i in v:
        lst=[]
        lst.append([k,i])

I dont know why but I get only this:

lst=[[10,2]]

Upvotes: 1

Views: 3092

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

lst=[]
lst.append([k,i])

is the same as

lst=[k,i]

Not very useful in a loop.

To avoid those initialization bugs, "flatten" your dictionary like this (create an artificial list for the key just to be able to add it to the values in a list comprehension):

d={10:[2,"str1",4] , 20:[5,"str2",7] , 30:[8,"str3",10]}

print([[k]+v for k,v in d.items()])

note that the order in the list isn't guaranteed, since order in dicts isn't guaranteed (unless you're using a version where dictionaries keep order like CPython 3.6)

Upvotes: 4

Related Questions