Perform operation on some (not all) dictionary values

℡╲_俬逩灬. 提交于 2019-12-11 11:04:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!