Igor
Igor

Reputation: 6267

Modifying tuple element from the dictionary

I have a following dictionary as input:

my_dict[(1, 2)] = (3,4)

Now what I want to have convert it to is:

my_dict[(1,2)] = (3,40)

What is the best and efficient way to do this?

The dictionary itself is not very big...

I could probably do something like:

for (var1,var2),(var3,var) in my_dict.iteritems():
    del my_dict[(var1,var2)]
    my_dict[(var1,var2)] = (var3, var5)

but I don't think its right approach as I modify the dictionary in a loop.

Upvotes: 0

Views: 44

Answers (3)

Arrahed
Arrahed

Reputation: 101

You could do something like this:

my_dict[(1, 2)] = (3,4)
my_Dict2={i:(j[0],j[1]*10) for i,j in my_Dict.items()}

But I'm not sure if this is what your looking for since 'var5' in your code snippet is not defined. However, if you need to modify a tuple, there is probably a better type to use.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1123440

You can just assign directly to the key; no need to delete the key first.

You could loop over the dictionary, yielding keys (your tuples); no need to unpack these even:

for key in my_dict:
    my_dict[key] = (my_dict[key][0], var5)

or include the values:

for key, (val1, _) in my_dict.iteritems():
    my_dict[key] = (val1, var5)

This unpacks just the value so you can reuse the first element. I've used _ as the name for the second value element to document it'll be ignored in the loop.

Upvotes: 2

sundar nataraj
sundar nataraj

Reputation: 8702

    my_dict={}
    my_dict[(1, 2)] = (3,4)

    for i,val in my_dict.items():

        my_dict[i]=(3,24)
    print my_dict

    #output {(1, 2): (3, 24)}

other way.

    for i in my_dict.keys():

        my_dict[i]=(3,24)
    print my_dict

also

for i in my_dict:

    my_dict[i]=(3,24)
print my_dict

Upvotes: 1

Related Questions