[英]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.我想遍历每个交易所,然后遍历所有价格并根据
side
更改它们。 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). if
side: bid
我想将该price
乘以一个数字(例如:0.99),如果side: ask
我想将该价格乘以一个不同的数字(例如: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.谢谢您的帮助。
You could use a dict
here to hold the price multipliers, and iterate through all orders with nested for loops.您可以在此处使用
dict
来保存价格乘数,并使用嵌套的 for 循环遍历所有订单。
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"]]
The way to do this as a comprehension would be:作为理解来做到这一点的方法是:
{k: [
{**order, 'price': (
order['price'] * 0.99
if order['side'] == 'ask'
else order['price'] * 1.01
)}
for order in exchange
] for k, exchange in exchanges.items()}
I am quite new to python so forgive me if I am doing this wrong:我对 python 很陌生,所以如果我做错了,请原谅我:
def iterFunc(dic,bidf=0.99,askf=1.01):
for exchange in dic:
for part in dic[exchange]:
ty = part['side']
if ty == "bid":
part['price'] *= bidf
elif ty == "ask":
part['price'] *= askf
I made a function instead in which "dic" is the dictionary with the nested dictionaries.我做了一个 function 而不是其中“dic”是带有嵌套字典的字典。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.