我有一个嵌套的字典,看起来像下面的
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},
}
所需的排序字典如下所示
[(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'])])]
它是2个元组的列表,第一个索引是按递减级别排序的技能水平,第二个索引是2个元组的另一个列表,其中包含它们的名称作为其中的另一个列表。我是否需要从原始词典中提取信息并构建一个全新的元组列表?或者我只需要简单地将原始字典更改为2个元组的列表
答案 0 :(得分:1)
您可以构建一个中间字典,然后使用它来产生最终输出,如下所示:
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)
礼物:
[(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'])])]
(注意:也许可以使用某种嵌套的defaultdict
来避免显示此处的两个if
语句,但是我没有尝试过。如果您做了d=defaultdict(dict)
,这样可以避免第一个if
语句,但第二个仍将保留。)