简体   繁体   中英

Python create nested dictionary from list with nested tuples

Thank you for your help. Still very new to python. I trust I'm not abusing the goodwill of SO with such questions. I am trying to evolve from SQL database mentality to a python lists/dictionary approach.

Here is a snippet of a list with nested tuples (always containing three elements):

List = [(u'32021', u'161', 1696.2), (u'32021', u'162', 452.2), (u'32044', u'148', 599.2), (u'32044', u'149', 212.2)]

Can this be converted to a dictionary with nested dictionaries, something like this:

{'32021': ('161': 1696.2, '162': 452.2), '32044': ('148': 599.2, '149': 212.2)}

I addressed a similar problem that only had two items in each tuple using:

d = defaultdict(list)
for k, v in values:
    d[k].append(v)

For three items, is one solution using indexing with a for loop?

Thank you.

You probably want this:

d = {}
for k1,k2,v in List:
     d[(k1,k2)] = v

or even this:

d = {(k1,k2):v  for k1,k2,v in List}

you can do this case with a nested defaultdict:

d = defaultdict(lambda:defaultdict(list))

for k1, k2, v in values:
    d[k1][k2].append(v)

print d['32044']['148']
[599.2]

etc.

Also, see the bunch pattern, which is an easy-to-use similar idea that even lets you assign attributes inline without having to declare them first: https://pypi.python.org/pypi/bunch/1.0.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