curious_cosmo
curious_cosmo

Reputation: 1214

Perform operation on some (not all) dictionary values

I have a dictionary called spectradict which is composed of 5 different keys (multiple values per key), and I'd like to multiply each value under 4 of the keys by some constant A. I've figured out how to multiply all the values (under all the keys) by the constant:

spectradict.update((x, y*A) for x, y in spectradict.items())

But I only want the values under spectradict['0.001'], spectradict['0.004'], spectradict['0.01'], spectradict['0.02'] to be multiplied by A. I want the spectradict['E'] values to remain unchanged. How can I accomplish this?

Upvotes: 1

Views: 55

Answers (2)

Robᵩ
Robᵩ

Reputation: 168706

You can list the keys explicitly:

#UNTESTED
spectradict.update((x, spectradict[x]*A) for x in ['0.001', '0.004', '0.01', '0.02'])

Or, you could just exclude E:

#UNTESTED
spectradict.update((x, y*A) for x, y in spectradict.items() if x != 'E')

Upvotes: 1

SCB
SCB

Reputation: 6149

You can perform conditional checks on your generator function by appending if <test> to the end of it.

spectradict.update((k, v*A) for k, v in spectradict.items() if k != 'E')
# or, inclusive test using a set
spectradict.update((k, v*A) for k, v in spectradict.items() if k in {'0.001', '0.004', '0.01', '0.02'})

Upvotes: 1

Related Questions