【问题标题】:Append elements to multiple keys of a Python dictionary将元素附加到 Python 字典的多个键
【发布时间】:2019-02-25 16:01:03
【问题描述】:

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

# 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)

【问题讨论】:

  • 这有什么改进?
  • @KlausD。假设我没有三把钥匙,而是一百把。我不想写一百行来为键提供新元素。我想在一行中只输入一个数组或一个列表。
  • 如果你有一百个键,你可能会使用某种循环而不是复制/粘贴 100 条几乎相同的行。在一行中对 100 个不同的键执行 100 次附加操作很难读取,不是吗?
  • 在某些时候,您必须定义数百个键及其数百个表达式。
  • 差不多。我可能会创建一个像{'Key1': lambda i: i, 'Key2': lambda i: -i, 'Key3': lambda i: i^2} 这样的函数的字典并循环遍历该字典。

标签: python loops dictionary append


【解决方案1】:

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

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

# 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 的建议。请记住,虽然这个示例运行良好,但如果您要与其他人共享您的代码,那么可读性是一件很重要的事情,所以不要害怕保持简单,没有太多收获!

【讨论】:

    【解决方案2】:

    您可以继承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]}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-22
      • 1970-01-01
      • 1970-01-01
      • 2016-04-04
      • 2017-01-15
      • 1970-01-01
      • 2016-01-21
      相关资源
      最近更新 更多