e9e9s e9e9s - 7 months ago 32
Python Question

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 (e.g.
['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?

Answer Source

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