简体   繁体   中英

Turn a list of lists of lists of lists into a dictionary

I'm using Python 3.6 and I need to turn the list below into a dictionary of dictionaries:

myList = [['A',[['a',1],['b',0],['c',1]]],['B',[['a',0],['b',1],['c',1]]]]

Output:

myDict = {A: {a: 1, b: 0, c: 1}, B: {a: 0, b: 1, c: 1}}

I tried to use:

myDict = defaultdict(lambda: defaultdict(list))
for key1, key2, *values in myList:
    myDict[key1][key2].extend(values)

But I get an error:

TypeError: unhashable type: 'list'

Comprehensions got your back:

{ k:{ kk:vv for kk, vv in v } for k, v in myList }
# => {'A': {'a': 1, 'b': 0, 'c': 1}, 'B': {'a': 0, 'b': 1, 'c': 1}}

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