问题
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?
回答1:
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'})
回答2:
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')
来源:https://stackoverflow.com/questions/49120684/perform-operation-on-some-not-all-dictionary-values