简体   繁体   中英

Convert nested dictionary into list of tuples

I have a nested dictionary that looks like the following

db1 = {
        'Diane':   {'Laundry': 2,   'Cleaning': 4, 'Gardening': 3},
        'Betty':   {'Gardening': 2, 'Tutoring': 1, 'Cleaning': 3},
        'Charles': {'Plumbing': 2,  'Cleaning': 5},
        'Adam':    {'Cleaning': 4,  'Tutoring': 2, 'Baking': 1},
        }

The desired sorted dictionary looks like the following

[(5, [('Cleaning', ['Charles'])]),
(4, [('Cleaning', ['Adam', 'Diane'])]),
(3, [('Cleaning', ['Betty']), ('Gardening', ['Diane'])]),
(2, [('Gardening', ['Betty']), ('Laundry', ['Diane']),
 ('Plumbing', ['Charles']), ('Tutoring', ['Adam'])]),
(1, [('Baking', ['Adam']), ('Tutoring', ['Betty'])])]

it is a list of 2 tuples, the first index is the skill level sorted by decreasing level and the second index is another list of 2 tuple which contains their names as another list inside it. Do I need to extract info from the original dictionary and build a completely new list of tuples? Or I just need to simply change original dictionary into a list of 2 tuple

You can build up an intermediate dictionary, and then use it to produce your final output, as follows:

from pprint import pprint

db1 = {
        'Diane':   {'Laundry': 2,   'Cleaning': 4, 'Gardening': 3},
        'Betty':   {'Gardening': 2, 'Tutoring': 1, 'Cleaning': 3},
        'Charles': {'Plumbing': 2,  'Cleaning': 5},
        'Adam':    {'Cleaning': 4,  'Tutoring': 2, 'Baking': 1},
        }

d = {}

for k, v in db1.items():
    for kk, vv in v.items():
        if vv not in d:
            d[vv] = {}
        if kk not in d[vv]:
            d[vv][kk] = []
        d[vv][kk].append(k)

out = sorted([(k,
               [(kk, sorted(v[kk])) for kk in sorted(v.keys())])
              for k, v in d.items()],
             key=lambda t:t[0],
             reverse=True)

pprint(out)

Gives:

[(5, [('Cleaning', ['Charles'])]),
 (4, [('Cleaning', ['Adam', 'Diane'])]),
 (3, [('Cleaning', ['Betty']), ('Gardening', ['Diane'])]),
 (2,
  [('Gardening', ['Betty']),
   ('Laundry', ['Diane']),
   ('Plumbing', ['Charles']),
   ('Tutoring', ['Adam'])]),
 (1, [('Baking', ['Adam']), ('Tutoring', ['Betty'])])]

(Note: it might be possible to use some kind of nested defaultdict to avoid the two if statements shown here, but I have not attempted this. If you did d=defaultdict(dict) , that would avoid the first if statement, but the second would remain.)

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