python - 为什么我无法为字典元素重新分配值但可以附加到它?

标签 python python-3.x list dictionary key

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

如果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']}

More details list append method

关于python - 为什么我无法为字典元素重新分配值但可以附加到它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56702841/

相关文章:

python - Pyapns 故障 500 : 'Connection to the APNS server could not be made

python - 用 1D numpy 数组创建 2D

继承类方法中的Python递归

Python 等待一个内部有循环的函数

python - 有效地将平面列表分割为多级嵌套列表

python - 我可以列出 python 中的方法吗?

python - 自动更新键字典到整数映射

python - PVLIB - 如何使用耦合逆变器正确定义系统规模

string - 将字符串转换为字符串序列

python - 数组解释的循环旋转