简体   繁体   English

替换列表/元组python字典中的值

[英]Replace a value in a dictionary of lists/tuples python

I have a dictionary like so: 我有这样的字典:

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

I want to write a function to allow me to update the list portion of the value (eg ['af1','af2','af3'] ). 我想编写一个函数来更新值的列表部分(例如['af1','af2','af3'] )。 The code below works to filter by the different values to get to the correct list within the value: 下面的代码用于过滤不同的值,以获取该值内的正确列表:

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

I want to add something like di.update(i[2], new_lst) My question is how can I update ONLY the list value with a new list? 我想添加类似di.update(i[2], new_lst)问题。我的问题是如何仅使用新列表更新列表值?

Since tuple is an immutable type, you cannot change a single entry in the tuple. 由于元组是不可变的类型,因此您不能更改元组中的单个条目。 A workaround is to create a list with the elements you would like to have in the tuple, and then create a tuple from the list. 一种解决方法是使用元组中想要的元素创建一个列表,然后从列表中创建一个元组。 You will also have to assign the new tuple to the given element in the parent-list, like this: 您还必须将新元组分配给父列表中的给定元素,如下所示:

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

(I was a little confused by your example, in which the variables called tuple_a and tuple_b were actually strings. It might have been better to call them name_a and name_b or similar.) (您的示例让我有些困惑,在该示例中,称为tuple_a和tuple_b的变量实际上是字符串。最好将它们命名为name_a和name_b或类似名称。)

As other mentioned you can not change a single entry in the tuple. 如前所述,您不能在元组中更改单个条目。 But the list within the tuple is still mutable. 但是元组中的列表仍然是可变的。

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

So for what you want, you can do something like: 因此,对于您想要的东西,您可以执行以下操作:

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

So in your code replace the # di.update(i[2], new_lst) with 因此,在您的代码中,将# di.update(i[2], new_lst)替换为

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

And I think this is faster too. 而且我认为这也更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM