我有一个要求,我必须基本上反转 keys
和values
在字典里。
如果key
已经存在,它应该将新元素值附加到现有元素值。
我为此编写了代码。它运行良好。但是,如果我重新分配字典项而不是附加它,使用新元素,而不是覆盖,它会创建 None
代替值(value)。
这是工作代码:
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))
Correct Output: {'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))
Incorrect Output: {'Stan': ['Code.py'], 'Randy': None}
我不确定重新分配字典元素值和附加现有值之间是否有任何区别。
有人请澄清一下。
最佳答案
替换 for 循环:
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]
致
for key, value in files.items():
# if dictionary has same key append value
if value in list(dt.keys()):
dt[value].append(key)
else:
dt[value] = [key]
或
将项目添加到列表末尾。相当于a[len(a):] = [x]
for key, value in files.items():
if value in list(dt.keys()):
dt[value][len(dt[value]):] = [key]
else:
dt[value] = [key]
O/P:
{'Randy': ['Input.txt', 'Output.txt'], 'Stan': ['Code.py']}
关于python - 为什么我无法为字典元素重新分配值但可以附加到它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56702841/