我正在尝试从字典中获取值,但值是列表 例如:
dict_1 = {A:[2,3,4], B:[3,4,5], C:[6,7,8]}
现在我试图遍历字典并获取它的值除以任何整数并返回该值以形成另一个字典
dict_2 = {A:[2/x, 3/x, 4/x], B:[3/x, 4/x, 5/x], C:[6/x, 7/x, 8/x]}
答案 0 :(得分:3)
如果要创建新词典,可以使用词典理解:
dict_2 = {k: [y/float(x) for y in v] for k, v in dict_1.items()}
否则,您可以使用 for 循环:
for k, v in dict_1.items():
dict_1[k] = [y/float(x) for y in v]
答案 1 :(得分:3)
你可以使用词典理解:
>>> from __future__ import division # only required for python 2 (but doesn't hurt on Python 3)
>>> dict_1 ={'A':[2,3,4],'B':[3,4,5],'C':[6,7,8]}
>>> x = 2
>>> {key: [val/x for val in value] for key, value in dict_1.items()}
{'A': [1.0, 1.5, 2.0], 'B': [1.5, 2.0, 2.5], 'C': [3.0, 3.5, 4.0]}