Changing tuple in list in dictionary

Viewed 211
D = {'A':
        [ ( '1','2' ), ( '3', '4' )],
     'B':
        [ ( '5','6' ), ( '7','8' ) ]
    }

x = '6'

for key in D:
    for val in D[key]:
        if x in val:
            val=('50','60')
        
print(D)

Hello, I want to make a change at the value of key B, but I wonder why it does not print this:

    D = {'A':
            [ ( '1','2' ), ( '3','4' ) ],
         'B':
            [ ( '50','60' ), ( '7','8' ) ]
        }

How can I fix it?

4 Answers

By doing val=('50','60') you replace the variable itself, not the content of the list.

for d_val in D.values():
    for rank, val in enumerate(d_val):
        if x in val:
            d_val[rank] = ('50', '80')

val is a local reference to the element. When you overwrite it, you just assign a new tuple to that variable - it has nothing to do with the list that contains it. Instead, you could loop of the list's indexes and update the list directly:

for key in D:
    for i in range(len(D[key])):
        if x in D[key][i]:
            D[key][i] = (50,50)

You can use dictionary comprehension to get this done in one line.

Here's your code to define the dictionary d and value x

d = {'A':
        [ ( '1','2' ), ( '3', '4' )],
     'B':
        [ ( '5','6' ), ( '7','8' ) ]
    }
x = '6'

The below one line of code will create the dictionary d again with the new value. To show you that d and r are different only by a small difference, I have retained dictionary d.

r = {k:[(50,60) if x in i else i for i in d[k]] for k in d.keys()}

To ensure there is only one change, I am printing both d and r.

print (d)
print (r)

The output will be as follows:

{'A': [('1', '2'), ('3', '4')], 'B': [('5', '6'), ('7', '8')]}
{'A': [('1', '2'), ('3', '4')], 'B': [(50, 60), ('7', '8')]}

Tuples cannot be edited. There you go! Have a nice day!

Related