클래스/유형을 포함하지 않고 중첩된 defaultdict를 인쇄하는 방법은 무엇입니까? (How to print a nested defaultdict without including the class/type?)


문제 설명

클래스/유형을 포함하지 않고 중첩된 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 newbiecoder11blhsing)

참조 문서

  1. How to print a nested defaultdict without including the class/type? (CC BY‑SA 2.5/3.0/4.0)

#defaultdict #Sorting #Python






관련 질문

많이 중첩 된 defaultdict에서 물건을 계산하는보다 Pythonic 방법 (More Pythonic way of counting things in a heavily nested defaultdict)

GAE ndb에서 산세척 (Pickling on GAE ndb)

파이썬을 사용하여 구분된 문자열 목록을 트리/중첩 사전으로 변환 (convert a list of delimited strings to a tree/nested dict, using python)

Python에서 defaultdict 또는 dict를 Ordereddict로 변환할 수 있습니까? (Can I convert a defaultdict or dict to an ordereddict in Python?)

기본 사전의 각 키를 고유한 CSV 파일에 쓰기 (Writing each key in a default dict to a unique csv file)

TypeError: 첫 번째 인수는 호출 가능해야 합니다. defaultdict (TypeError: first argument must be callable, defaultdict)

defaultdict(list)를 Pandas DataFrame으로 변환하는 방법 (How to convert a defaultdict(list) to Pandas DataFrame)

여러 매개변수가 있는 defaultdict (defaultdict with multiple parameters)

함께 사용되는 Defaultdict 및 람다 함수 (Defaultdict and lambda function used together)

클래스/유형을 포함하지 않고 중첩된 defaultdict를 인쇄하는 방법은 무엇입니까? (How to print a nested defaultdict without including the class/type?)

dict에서 빈 세트를 제거하는 간단한 방법 (Simple way to remove empty sets from dict)

특정 키를 포함하는 많은 defaultdicts의 값 가져오기 (Getting the values of many defaultdicts that contains a certain key)







코멘트