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

时间:2018-09-21 09:12:36

标签: python loops dictionary 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]}

但是,我想做的就是将所有这些新元素添加到一行中,就像这样:

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

2 个答案:

答案 0 :(得分:0)

有很多方法可以解决此问题,但又不要太花哨,这是首先想到的方法。

请注意,随着密钥的更新,您将需要维护不断扩大的操作列表。

# 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的建议。请记住,尽管此示例很好用,但是如果您要与其他人共享代码,那么可读性是一件大事,因此不要害怕简单,就没有太多收获! / p>

答案 1 :(得分:0)

当参数为元组时,您可以继承dict的子类并覆盖__getitem__以返回自定义类的对象,以便自定义类可以附加一个append方法一键拍摄与给定键对应的值:

class Dict(dict):
    class DictView:
        def __init__(self, d, keys):
            self.d = d
            self.keys = keys

        def append(self, *items):
            for key, item in zip(self.keys, items):
                self.d[key].append(item)

    def __getitem__(self, key):
        if isinstance(key, tuple):
            return self.DictView(self, key)
        return super().__getitem__(key)

这样:

my_dict = Dict({'Key1': [0], 'Key2': [0], 'Key3': [0]})
for i in range(1, 5):
    my_dict['Key1', 'Key2', 'Key3'].append(i, -i, i^2)
print(my_dict)

将输出:

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