首页 > 解决方案 > 如何从列表中向字典键添加第二个值?

问题描述

我正在尝试从包含元组(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()}

标签: pythonlistdictionarytuples

解决方案


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

推荐阅读