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':
Solution 1:
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
}
forordersin exchanges.values():
fororderin orders:
order["price"] *= price_multipliers[order["side"]]
Solution 2:
The way to do this as a comprehension would be:
{k: [
{**order, 'price': (
order['price'] * 0.99if order['side'] == 'ask'
else order['price'] * 1.01
)}
fororderin exchange
] fork, exchange in exchanges.items()}
Solution 3:
I am quite new to python so forgive me if I am doing this wrong:
def iterFunc(dic,bidf=0.99,askf=1.01):
for exchange in dic:
for part in dic[exchange]:
ty = part['side']
ifty== "bid":
part['price'] *= bidf
elifty== "ask":
part['price'] *= askf
I made a function instead in which "dic" is the dictionary with the nested dictionaries.
Post a Comment for "Python How To Iterate Over Nested Dictionary And Change Values?"