python - 如何从列表中向字典键添加第二个值?
问题描述
我正在尝试从包含元组(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 有一个漂亮的字典方法,叫做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
推荐阅读
- merge - 在 SNOWFLAKE 中进行横向展平时重复主键
- angular - 角度嵌套导航和路由器插座
- python - 在 Replit 中保存游戏并加载以从保存的位置开始
- jquery - 查找完全没有属性的元素
- javascript - 尽管之间有内容,为什么 Textarea 是空的
- api - 您无权访问“http://us-south.assistant.watson.cloud.ibm.com”
- c++ - 在 0 到 100 之间进行简单的猜谜游戏,但猜中 2 次后游戏结束
- grails - 使用 Grails 4/5 在已部署的应用程序中重新加载 gsp
- proxy - SonarQube Scanner 的 Jenkins 工具的自动安装似乎忽略了 Jenkins 的代理设置
- python - 硒文本选择的异常索引问题