【问题标题】:Why am I not able to re-assign a value to a dictionary element but can append to it? [duplicate]为什么我无法为字典元素重新分配值但可以附加到它? [复制]
【发布时间】:2019-06-21 11:47:19
【问题描述】:

我有一个要求,我必须在字典中基本上反转 keysvalues

如果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


【解决方案1】:

替换你的 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']}

More details list append method

【讨论】:

  • 谢谢。但我问的是@roganjosh 解释的这两者之间的区别
  • 这正是他们已经拥有的。问题是为什么第二个版本不起作用
猜你喜欢
  • 2017-02-01
  • 2016-04-05
  • 1970-01-01
  • 2021-12-26
  • 2019-08-14
  • 1970-01-01
  • 2017-06-02
  • 1970-01-01
  • 2022-01-07
相关资源
最近更新 更多