Python如何遍历嵌套字典并更改值? [英] Python how to iterate over nested dictionary and change values?

查看:133
本文介绍了Python如何遍历嵌套字典并更改值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据如下所示

{'exchange1': [{'price': 9656.04, 'side': 'bid', 'size': 0.16, 'timestamp': 1589504786}, 
               {'price': 9653.97, 'side': 'ask', 'size': 0.021, 'timestamp': 1589504786}], 
'exchange2': [{'price': 9755.3, 'side': 'bid', 'size': 27.0, 'timestamp': 1589504799},
              {'price': 9728.0, 'side': 'bid', 'size': 1.0, 'timestamp': 1589504799}]}

我想遍历每个交易所,然后遍历所有价格,并根据side键更改它们. 如果side : bid我想将price乘以一个数字(例如:0.99),而side : ask我想将价格乘以另一个数字(例如:1.01).

I want to iterate over each exchange and then for all prices and change them depending on the side key. If side : bid I want to multiply that price by a number (ex: 0.99) and if side : ask I want to multiply the price by a different number (ex: 1.01).

我不确定如何在包含边数和价格数据的字典列表上进行迭代.

I am not sure how to iterate on the list of dictionaries that contain the side and price data.

谢谢您的帮助.

推荐答案

您可以在此处使用dict来保存价格乘数,并使用嵌套的for循环遍历所有订单.

You could use a dict here to hold the price multipliers, and iterate through all orders with nested for loops.

exchanges = {
    'exchange1': [{'price': 9656.04, 'side': 'bid', 'size': 0.16, 'timestamp': 1589504786},
                  {'price': 9653.97, 'side': 'ask', 'size': 0.021, 'timestamp': 1589504786}],
    'exchange2': [{'price': 9755.3, 'side': 'bid', 'size': 27.0, 'timestamp': 1589504799},
                  {'price': 9728.0, 'side': 'bid', 'size': 1.0, 'timestamp': 1589504799}]
}

price_multipliers = {
    'bid': 0.99,
    'ask': 1.01
}

for orders in exchanges.values():
    for order in orders:
        order["price"] *= price_multipliers[order["side"]]

这篇关于Python如何遍历嵌套字典并更改值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆