python - 将元素追加到 Python 字典的多个键

标签 python loops dictionary append

我正在尝试将元素 append 到循环中的多个字典键。但是,现在我认为要做到这一点还有很长的路要走 - 每个关键更新都需要单独一行,例如:

# My dictionary
my_dict = {'Key1': [0], 'Key2': [0], 'Key3': [0]}

# Show initial state
print(my_dict)

# Populate dictionary with new elements
for i in range(1, 5):
    my_dict['Key1'].append(i)
    my_dict['Key2'].append(-i)
    my_dict['Key3'].append(i^2)

# Show final result
print(my_dict)

这给出了所需的

{'Key1': [0, 1, 2, 3, 4], 'Key2': [0, -1, -2, -3, -4], 'Key3': [0, 3, 0, 1, 6]}

但是,我想做的是将所有这些新元素 append 在一行中,如下所示:

for i in range(1, 5):
    my_dict['Key1', 'Key2', 'Key3'].append(i, -i, i^2)

最佳答案

有很多方法可以实现这一点,但不要太花哨,这是首先想到的方法。

请注意,您必须在更新 key 时维护不断扩展的操作列表。

# My dictionary
my_dict = {'key1': [0], 'key2': [0], 'key3': [0]}

# Show initial state
print(my_dict)

# Populate dictionary with new elements
for i in range(1, 5):
    key_update_operation = {'key1': i, 'key2': -i, 'key3': i^2}
    for k, v in my_dict.items():
        my_dict[k].append(key_update_operation[k])

# Show final result
print(my_dict)

我认为这基本上就是 @Aran-Fey 的建议。请记住,虽然这个示例运行得很好,但如果您要与其他人共享您的代码,可读性是一件很重要的事情,所以不要害怕保持简单,没有太多收获!

关于python - 将元素追加到 Python 字典的多个键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52440403/

相关文章:

python - 在新型类中实现 __getitem__

python - 类型错误 : get() takes 2 positional arguments but 3 were given

python - tkinter Treeview 所选项目的点击事件

javascript读取前五个值

c - while(true) 和 for(;;) 之间有什么区别?

java - 在java中,无效输入继续后重新提示用户的循环

c# - 搜索字典值并返回满足条件的键列表

python - 使列表python具有 key 对

swift - 将字典中的整数相加

python - defaultdict 带有类构造函数的参数