python反转str的字典:str的列表

时间:2014-03-23 04:14:11

标签: python dictionary

我需要编写一个接受字典{name:[sports club]}的函数,并反转所有值并返回一个反转值的字典{sports club:[names]}。例如,

如果字典是:

name_to_club = {'Raymond Joe' : ['Volleyball', 'Football'], 'Joana Jackson': ['Gymnastics'], 'Anthony Jackson': ['Football', 'Basketball'], 'Sonia Smith': ['Gymnastics', 'Badminton']}

该函数应返回:

    {'Volleyball': ['Raymond Joe'], 'Gymnastics': ['Joana Jackson', 'Sonia Smith'], 'Basketball': ['Anthony Jackson'], 'Badminton': ['Sonia Smith'], 'Football': ['Raymond Joe', 'Anthony Jackson']}

我在下面编写了一个函数,但它只为每项运动返回一个名称,而不是每个运动名称。所以它给了:

{'Volleyball': ['Raymond Joe'], 'Gymnastics': ['Joana Jackson'], 'Basketball': ['Anthony Jackson'], 'Badminton': ['Sonia Smith'], 'Football': ['Raymond Joe']}

我似乎无法包括属于同一个体育俱乐部的每个人,而且我只是python的初学者所以我会感激任何帮助而不会让它复杂化!

def club_to_name(name_to_club):
    lst = []
    dic = {}

    for value in name_to_club.values():
        for c in value:
            if c not in lst:
                lst.append(c)
                new = set(lst)
                for eachitem in new:
                    for key, value in name_to_club.items():
                        if eachitem in value:
                            dic.update({eachitem:[key]})                         
    return dic

2 个答案:

答案 0 :(得分:1)

Python 2.7.6 (default, Feb 26 2014, 13:22:43) 
>>> name_to_club = {'Raymond Joe' : ['Volleyball', 'Football'], 'Joana Jackson': ['Gymnastics'], 'Anthony Jackson': ['Football', 'Basketball'], 'Sonia Smith': ['Gymnastics', 'Badminton']}
>>> result = {}
>>> for name, sports in name_to_club.items():
...     for sport in sports:
...             result.setdefault(sport, []).append(name)
... 
>>> result
{'Basketball': ['Anthony Jackson'], 'Football': ['Raymond Joe', 'Anthony Jackson'], 'Badminton': ['Sonia Smith'], 'Gymnastics': ['Sonia Smith', 'Joana Jackson'], 'Volleyball': ['Raymond Joe']}
>>> 

答案 1 :(得分:0)

使用defaultdict和sets

的变体
from collections import defaultdict

name_to_club = {'Raymond Joe' : ['Volleyball', 'Football'], 'Joana Jackson': ['Gymnastics'], 'Anthony Jackson': ['Football', 'Basketball'], 'Sonia Smith': ['Gymnastics', 'Badminton']}
inverted = defaultdict(set)
for name, sports in name_to_club.items():
    for sport in sports
        inverted.add(name)