lastnames到firstnames字典

时间:2017-11-17 02:34:32

标签: python list dictionary

所以我给了一个包含人们朋友圈子的字典,我应该根据他们的姓氏创建一个组织这些人的字典,即姓名字典的姓氏。

people_and_friends = {'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', 'Manny Delgado'], 'Claire Dunphy': ['Jay Pritchett', 'Mitchell Pritchett', 'Phil Dunphy'], 'Manny Delgado': ['Gloria Pritchett', 'Jay Pritchett', 'Luke Dunphy'], 'Mitchell Pritchett': ['Cameron Tucker', 'Claire Dunphy', 'Luke Dunphy'], 'Alex Dunphy': ['Luke Dunphy'], 'Cameron Tucker': ['Gloria Pritchett', 'Mitchell Pritchett'], 'Haley Gwendolyn Dunphy': ['Dylan D-Money', 'Gilbert D-Cat'], 'Phil Dunphy': ['Claire Dunphy', 'Luke Dunphy'], 'Dylan D-Money': ['Chairman D-Cat', 'Haley Gwendolyn Dunphy'], 'Gloria Pritchett': ['Cameron Tucker', 'Jay Pritchett', 'Manny Delgado'], 'Luke Dunphy': ['Alex Dunphy', 'Manny Delgado', 'Mitchell Pritchett', 'Phil Dunphy']}

这是我到目前为止的代码,它隔离了第一个字典中个体的姓氏:

lastnames_to_firstnames = {}

for people in person_and_friends:
    family = person[person.rfind(' '):].strip()
    if not family in lastnames_to_firstnames:
        lastnames_to_firstnames[family_name] = person_and_friends[people]

lastnames_to_firstnames应如下所示:

lastname_firstname = {'Pritchett':['Jay', 'Gloria', 'Mitchell'], 
'Dunphy':['Alex', 'Claire', 'Haley Gwendolyn', 'Luke', 'Phil'], 
'Delgado':['Manny'],'Tucker':['Cameron'],'D-Money':['Dylan'], 'D-Car':
['Chairman']}

我无法弄清楚如何组织第一个字典的值。有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

使用defaultdict

from collections import defaultdict

d = defaultdict(list)

people_and_friends = {'Joseph Hazelton': ['Penny Patrick', 'Paul Paulson'], 
                     'Gilbert Gunderson': ['Philip Patrick', 'Jenny Paulson'], 
                     'Helena Anderson': ['Penny Patrick', 'Dylan D-Money']}

for k, v in people_and_friends.items():
    for first, last in map(str.split, (k, *v)):
        d[last].append(first)

编辑:

正如TitanFighter在下面指出的那样,如果你想避免重复名称配对,你可以使用set代替

d = defaultdict(set)

d[last].add(first)

编辑第二个:

如果你不能使用defaultdict,你可以像这样自己动手

d = {}

people_and_friends = {'Joseph Hazelton': ['Penny Patrick', 'Paul Paulson'], 
                     'Gilbert Gunderson': ['Philip Patrick', 'Jenny Paulson'], 
                     'Helena Anderson': ['Penny Patrick', 'Dylan D-Money']}

for k, v in people_and_friends.items():
    for first, last in map(str.split, (k, *v)):
        if last in d:
            d[last].append(first)
        else:
            d[last] = [first]

3dit:

问题是你词典中的某些人有三个名字:Haley Gwendolyn Dunphy。所以我们要做的是将除最后一个名称之外的所有名称收集到列表中,然后再将该列表再次加入字符串

d = {}

for k, v in people_and_friends.items():
    for *first, last in map(str.split, (k, *v)):
        first = ' '.join(first)
        if last in d:
            d[last].add(first)
        else:
            d[last] = {first}