【发布时间】:2019-06-21 11:47:19
【问题描述】:
我有一个要求,我必须在字典中基本上反转 keys 和 values。
如果key 已经存在,它应该将新元素值附加到现有元素值。
我为此编写了一个代码。它工作正常。但是,如果我重新分配字典项而不是附加它,使用新元素而不是覆盖,它会创建 None 来代替值。
这是工作代码:
def group_by_owners(files):
dt = {}
for i,j in files.items():
if j in dt.keys():
dt[j].append(i) # Just appending the element
else:
dt[j]=[i]
return dt
files = {
'Input.txt': 'Randy',
'Code.py': 'Stan',
'Output.txt': 'Randy'
}
print(group_by_owners(files))
正确的输出:{'Stan': ['Code.py'], 'Randy': ['Input.txt', 'Output.txt']}
这是给出错误输出的代码:
def group_by_owners(files):
dt = {}
for i,j in files.items():
if j in dt.keys():
dt[j] = dt[j].append(i) # Re-assigning the element. This is where the issue is present.
else:
dt[j]=[i]
return dt
files = {
'Input.txt': 'Randy',
'Code.py': 'Stan',
'Output.txt': 'Randy'
}
print(group_by_owners(files))
不正确的输出:{'Stan': ['Code.py'], 'Randy': None}
我不确定重新分配字典元素值和附加现有值之间是否有任何区别。
有人,请澄清一下。
【问题讨论】:
-
append在原地工作,因此将None返回到dt[j] = dt[j].append(i) -
知道了。谢谢。
标签: python python-3.x list dictionary key