【问题标题】:Replace a value in a dictionary of lists/tuples python替换列表/元组python字典中的值
【发布时间】:2017-05-11 15:18:35
【问题描述】:

我有一本这样的字典:

d = {}
d['key1'] = [('tuple1a', 'tuple1b', ['af1', 'af2', 'af3']),
            ('tuple2a', 'tuple2b', ['af4', 'af5', 'af6']),
            ('tuple3a', 'tuple3b', ['af7', 'af8', 'af9'])]      

我想编写一个函数来更新值的列表部分(例如['af1','af2','af3'])。下面的代码用于过滤不同的值,以获取值中的正确列表:

def update_dict(dictionary, key, tuple_a, tuple_b, new_list=None):

    for k,v in dictionary.items():
        if key in k:
            for i in v:
                if tuple_a in i:
                    if tuple_b in i:
                        #di.update(i[2], new_lst) #this is what I'd like to do but can't get the right syntax
    return dictionary

我想添加类似di.update(i[2], new_lst) 的内容我的问题是如何仅使用新列表更新列表值?

【问题讨论】:

  • 它是一个元组字典。您不能更新元组。但我想知道您是否可以单独更改推荐列表。
  • 由于元组是不可变的,我可以像这样重新创建字典:d.update({k: [(tuple_a, tuple_b, aod_nt)]}) 但它创建的字典只有一个键:值对。如何保留字典中的其他值?
  • 我在 Stackoverflow 上的其他地方 posted an answer 描述了如何更改字典中列表中的值。

标签: python python-3.x dictionary tuples


【解决方案1】:

由于元组是不可变类型,您不能更改元组中的单个条目。一种解决方法是创建一个包含您希望在元组中包含的元素的列表,然后从列表中创建一个元组。您还必须将新元组分配给父列表中的给定元素,如下所示:

for k,v in dictionary.items():
    if key in k:
        for n,tpl in enumerate(v):
            if tuple_a in tpl and tuple_b in tpl:
                v[n] = tuple( list(tpl)[:-1] + [new_list] )

(我对您的示例感到有些困惑,其中名为 tuple_a 和 tuple_b 的变量实际上是字符串。将它们称为 name_a 和 name_b 或类似名称可能会更好。)

【讨论】:

    【解决方案2】:

    正如其他提到的,您不能更改元组中的单个条目。但是元组中的列表仍然是可变的。

    >>> my_tuple = ('a', 'b', 'c', [1, 2, 3, 4, 5], 'd')
    >>> my_tuple
    ('a', 'b', 'c', [1, 2, 3, 4, 5], 'd')
    >>> my_tuple[3].pop()
    5
    >>> my_tuple[3].append(6)
    >>> my_tuple
    ('a', 'b', 'c', [1, 2, 3, 4, 6], 'd')
    

    因此,对于您想要的,您可以执行以下操作:

    >>> my_tuple = ('a', 'b', 'c', [1, 2, 3, 4, 5], 'd')
    >>> newList = [10, 20, 30]
    >>>
    >>> del my_tuple[3][:]       # Empties the list within
    >>> my_tuple
    ('a', 'b', 'c', [], 'd')
    >>> my_tuple[3].extend(newList)
    >>> my_tuple
    ('a', 'b', 'c', [10, 20, 30], 'd')
    

    所以在你的代码中替换 # di.update(i[2], new_lst)

    del i[2][:]
    i[2].extend(new_list)
    

    而且我认为这也更快。

    【讨论】:

      猜你喜欢
      • 2010-11-07
      • 1970-01-01
      • 2016-03-21
      • 1970-01-01
      • 2021-12-12
      • 2019-02-23
      • 2020-07-11
      • 2019-04-07
      相关资源
      最近更新 更多