문제 설명
클래스/유형을 포함하지 않고 중첩된 defaultdict를 인쇄하는 방법은 무엇입니까? (How to print a nested defaultdict without including the class/type?)
다음 코드가 있습니다.
from collections import defaultdict
db1 = {'Adam': {'Cleaning': 4, 'Tutoring': 2, 'Baking': 1},
'Betty': {'Gardening': 2, 'Tutoring': 1, 'Cleaning': 3},
'Charles': {'Plumbing': 2, 'Cleaning': 5},
'Diane': {'Laundry': 2, 'Cleaning': 4, 'Gardening': 3}}
def by_skill(db1 : {str:{str:int}}) ‑> [int,[str,[str]]]:
order_skills = defaultdict(lambda:defaultdict(list))
for k,v in db1.items():
for key,value in v.items():
order_skills[value][key].append(k)
dict(order_skills)
order_skills_sorted = sorted( sorted(order_skills.items()), reverse=True )
return order_skills_sorted
if __name__ == '__main__':
print(by_skill(db1))
출력:
[(5, defaultdict(<class 'list'>, {'Cleaning': ['Charles']})), (4, defaultdict(<class 'list'>, {'Cleaning': ['Adam', 'Diane']})), (3, defaultdict(<class 'list'>, {'Cleaning': ['Betty'], 'Gardening': ['Diane']})), (2, defaultdict(<class 'list'>, {'Tutoring': ['Adam'], 'Gardening': ['Betty'], 'Plumbing': ['Charles'], 'Laundry': ['Diane']})), (1, defaultdict(<class 'list'>, {'Baking': ['Adam'], 'Tutoring': ['Betty']}))]
하지만 출력은 (필수 사항이 아니라 가독성을 위해 형식화됨): (알파벳 순으로) )
[(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'])])]
이렇게 하려면 sorted를 세 번째로 호출해야 하나요?
참조 솔루션
방법 1:
Since the ratings are ranged between 1 and 5, you can build a rating‑keyed dict of skill‑keyed dicts of lists of names and then iterate through the ratings to extract the names by skills in linear time:
by_skill = {}
for name, skills in db1.items():
for skill, rating in skills.items():
by_skill.setdefault(rating, {}).setdefault(skill, []).append(name)
print([
(
rating,
sorted(
(skill, sorted(names)) for skill, names in by_skill.get(rating, {}).items()
)
)
for rating in range(5, 0, ‑1)
])
This outputs:
[(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'])])]
(by newbiecoder11、blhsing)