Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a list of tuples to a dict with duplicate keys?

How can I convert list of tuples like:

query_res = [('a3','b6','c1'),
             ('a3','b6','c2'),
             ('a3','b6','c3'),
             ('a3','b7','c4'),
             ('a4','b8','c5'),
             ('a4','b8','c6')]

to a dict like:

result = {
    'a3': {
        'b6': ['c1', 'c2', 'c3'],
        'b7': ['c4']
    },
    'a4': {
        'b8': ['c5', 'c6']
    }
}

I have tried defaultdict, bug can only get inner dict, how can I map a to res here?:

res = defaultdict(list)
for a, b, c in query_res:
    res[b].append(c)
like image 308
zhwlx22 Avatar asked Dec 22 '22 22:12

zhwlx22


2 Answers

Using dict.setdefault

Ex:

query_res = [('a3','b6','c1'),
             ('a3','b6','c2'),
             ('a3','b6','c3'),
             ('a3','b7','c4'),
             ('a4','b8','c5'),
             ('a4','b8','c6')]

result = {}
for key, subkey, value in query_res:
    result.setdefault(key, {}).setdefault(subkey, []).append(value)

print(result)

Output:

{'a3': 
    {'b6': ['c1', 'c2', 'c3'], 
     'b7': ['c4']
     },
 'a4': 
    {'b8': ['c5', 'c6']
     }
}
like image 91
Rakesh Avatar answered Mar 30 '23 01:03

Rakesh


You can nest defaultdicts:

from collections import defaultdict
import pprint

d = defaultdict(lambda: defaultdict(list))

for a, b, c in query_res:
    d[a][b].append(c)

pprint.pprint(d)

Output:

defaultdict(<function <lambda> at 0x10acb1f28>,
            {'a3': defaultdict(<class 'list'>,
                               {'b6': ['c1', 'c2', 'c3'],
                                'b7': ['c4']}),
             'a4': defaultdict(<class 'list'>, {'b8': ['c5', 'c6']})})
like image 29
Chris_Rands Avatar answered Mar 30 '23 00:03

Chris_Rands