如何从列表中向字典键添加第二个值?

问题描述 投票:1回答:1

我正在尝试从包含元组(n1,n2)的列表中创建字典。为此,我编写了一个函数,该函数将列表作为参数并返回字典{'n1':{'n2'},等等。}我遇到的问题是列表包含具有相同键(n1)的多个元组但值(n2)不同。主要是,else语句似乎不起作用,我不确定为什么。

def construction_dict_amis(f_lst):
    """builds and returns a dictionary of people (keys) who declare all their friends (as values)
    f_lst: couple list(n1, n2): n1 has friend n2
    if n1 has more than 1 friend add another name to that key
    if for the couple (n1, n2) n2 does not declare any friends an empty set will be created
    """
    f = {}
    for n1, n2 in f_lst:
        if n1 not in n2:
            f[n1] = {n2}
        else:
            f[n1].extend(n2) #add n2 to n1 if n1 already present ?
        if n2 not in f:
            f[n2] = set()  # new entry first name2
    return f

print(construction_dict_amis([('Mike', 'Peter'),('Thomas', 'Michelle'),('Thomas', 'Peter')]))

预期输出:

{'Mike' : {'Peter'}, 'Peter' : set(), 'Thomas' : {'Michelle', 'Peter'}, 'Michelle' : set()}

实际输出:

{'Mike': {'Peter'}, 'Peter': set(), 'Thomas': {'Peter'}, 'Michelle': set()}
python list dictionary tuples
1个回答
1
投票

Python有一个漂亮的字典方法setdefault,这正是您想要的:

def construction_dict_amis(f_lst):
    f = {}
    for n1, n2 in f_lst:
        f.setdefault(n1, set()).add(n2) # Initiate friends of n1 if not initialized, and add n2 as friend
        f.setdefault(n2, set())         # Initiate firends of n2 if not initialized, and leave unchanged
    return f
© www.soinside.com 2019 - 2024. All rights reserved.