Search code examples
pythonloopsdictionarypython-itertools

Python how to iterate over nested dictionary and change values?


I have data that looks as follows

{'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}]}

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.

Thank you for your help.


Solution

  • 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"]]