【问题标题】:How to add second value to dictionary key from list?如何从列表中向字典键添加第二个值?
【发布时间】:2020-05-06 13:28:57
【问题描述】:

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

【问题讨论】:

  • 我希望得到AttributeError: 'set' object has no attribute 'extend'。你的意思是.add?另请注意,您似乎混淆了 fn1n2 - 也许更具描述性的名称会有所帮助。
  • {n2} 创建一个set,而不是字典或列表。根据上述注释,使用.add(n2)n2 添加到集合中。
  • @jonrsharpe,感谢您的评论。我没有收到该错误,是的,我尝试了 .add 并获得了相同的结果,我们 Thomas 仅与 Peter 一起列出。
  • 我认为您的意思是n1 not in f,即如果元组中的第一个人不在字典中,而不是n1 not in n2。另外,我不明白将第二个人的名字添加到字典背后的逻辑,但不理解他们与第一个人相关的事实。
  • @jonrsharpe 是的,这是我的错误。谢谢!

标签: python list dictionary tuples


【解决方案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

【讨论】:

  • 谢谢@Amitai Irron,看起来确实简单多了。
猜你喜欢
  • 2018-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-16
  • 1970-01-01
  • 1970-01-01
  • 2021-05-20
  • 2022-07-25
相关资源
最近更新 更多