简体   繁体   中英

List of Lists to Dictionary of Lists

I am having a hard time converting a list of lists to a dictionary of lists due to some of the key values being the same, I am also getting an issue with the null value. My List is:

L = [['shark', ['one']], ['shark',['two']], ['fish', ['one']], ['fish', ['two']], ['fish',[]]]

My desired dictionary of lists would be structured like this:

Dic = {'shark': ['one','two'], 'fish':['one', 'two', '0']} 

Is there any trick to be able to get the same key values to combine into a dictionary of lists like this?

L = [['shark', ['one']], ['shark',['two']], ['fish', ['one']], ['fish', ['two']], ['fish',[]]]

p = {}

for k, v in L:
    d = p.setdefault(k, [])
    if not v:v = ['0']
    d.extend(v)

print p

output:

{'shark': ['one', 'two'], 'fish': ['one', 'two', '0']}
from collections import defaultdict 
dct = defaultdict(list)
l = [['shark', ['one']], ['shark',['two']], ['fish', ['one']], ['fish', ['two']], ['fish',[]]]
for x in l:
    dct[x[0]].append(x[1])
dct
>>> defaultdict(list,
        {'fish': [['one'], ['two'], []], 'shark': [['one'], ['two']]})

if you need '0' instead of [] then add an if clause to the loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM