循环遍历列表中的多个字典,同时为增量变量赋值 - python

Loop through multiple dicts in list, while assigning values to incremental variables - python

x = [
   {'id': 'e5015', 'price': '2001.00000000', 'size': '0.30000000', 'time_in_force': 'GTC'}, 
   {'id': 'bdd3d', 'price': '2000.00000000', 'size': '0.10000000', 'time_in_force': 'GTC'}, 
   {'id': '32c60', 'price': '2000.00000000', 'size': '0.01770613', 'time_in_force': 'GTC'}
   {**insert varying number of additional dicts here**}
]

我们如何遍历这个字典列表,并根据字典的数量将它们分配给增量变量? (例如 z1、z2、z3、z4、z5 等)

z1 = x[0]["price1"]
z2 = x[0]["price2"]
z3 = x[0]["price3"]
z4 = x[0]["price4"]
...etc...
z9 = x[0]["price9"] # If it exists

How do we loop through this list of dicts, and assign them to incremental variables...

答案是:你不知道。看起来您正在尝试遍历字典,并且只保留价格信息。那么,为什么不列出价格呢?

prices = [d["price"] for d in x]

改为使用列表理解和列表索引来获取价格变量

prices = [d['price'] for d in x]
z1 = prices[0]
z2 = prices[1]
# ...etc