[英]Python how to iterate over nested dictionary and change values?
我的數據如下
{'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
更改它們。 if side: bid
我想將該price
乘以一個數字(例如:0.99),如果side: ask
我想將該價格乘以一個不同的數字(例如:1.01)。
我不確定如何迭代包含側面和價格數據的字典列表。
謝謝您的幫助。
您可以在此處使用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"]]
作為理解來做到這一點的方法是:
{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()}
我對 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
我做了一個 function 而不是其中“dic”是帶有嵌套字典的字典。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.