python - 通过将 orderDIct 值与 list[1] 相乘来更新它

标签 python

OrderedDict([('red', 10.0),('blue',45.5),('green',34.4)]
xList[(u'blue',1.5,u'car'),(u'green',1.9,u'bike'),(u'red', 10,u'boat')]

如何循环遍历orderedDict和List,通过将值乘以xList[1]来更新orderedDict值?

希望这是有道理的,我在过去的几个晚上一直在努力解决这个问题,任何帮助将不胜感激。

理想情况下我想回来:

OrderedDict[('red',100),('blue',68.25),('green',65.36)]

最佳答案

from collections import OrderedDict
d = OrderedDict([('red', 10.0),('blue',45.5),('green',34.4)])
xList = [(u'blue',1.5,u'car'),(u'green',1.9,u'bike'),(u'red', 10,u'boat')]
for tup in xList: # iterate over each tuple
    if tup[0] in d: # make sure key is in the dict
        d[tup[0]] *= tup[1] # multiply current value by the second element of the tuple

print(d)

OrderedDict([('red', 100.0), ('blue', 68.25), ('green', 65.36)])

关于python - 通过将 orderDIct 值与 list[1] 相乘来更新它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26920280/

相关文章:

python - 如何重新加载此模块?

python - 在 Python 中遍历一个 unicode 字符串

python - numpy 矩阵到 pandas 系列

python - 错误: [Errno 13] Permission denied: './configure' when use pip3 install matplotlib on termux

python - ValueError : Error when checking input: expected cu_dnnlstm_22_input to have 3 dimensions, 但得到形状为 (2101, 17) 的数组

python - 使用请求访问 url 时处理 Windows 身份验证

python - 尝试学习 F#...对整数列表进行排序

python - 如何将这个字符串(日志行)分割为多个不同的字符/模式?

python - 检查扭曲的返回值是否为 Deferred

python - 如何将带有不带引号的键的字符串转换为 Python 中的字典