-3
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**}
]

How do we loop through this list of dicts, and assign them to incremental variables depending on how many dicts there are? (eg. z1, z2, z3, z4, z5, etc)

z1 = x[0]["price1"]
z2 = x[0]["price2"]
z3 = x[0]["price3"]
z4 = x[0]["price4"]
...etc...
z9 = x[0]["price9"] # If it exists
  • 5
    Why do you think you want to do this? What advantage could multiple variables possibly have over a list in this case? – Paul M. Jun 25 '21 at 19:32
  • `x[0]["price1"]` will fail with a KeyError. You're neither looping through the list of dicts (it's always `x[0]`), nor getting a dict item out (since price1, price2, price3 etc don't exist as keys in the dicts). – 9769953 Jun 25 '21 at 19:33
  • They could possibly stay in the list, and perform the required math functions, but we would still need to be able to grab different 'price' and 'size' VALUES from dicts in the list that have identical KEYS (eg. 'price' is the same in each dict, but value of 'price' is not.) – Dakota Mac Dylan Carter MacBai Jun 25 '21 at 19:38
  • Can you explain what you are planning to do? – Hadas Arik Jun 25 '21 at 19:39
  • 1
    regarding z1, z2... z9 - check https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables It's a bad idea, use data structure – buran Jun 25 '21 at 19:51
  • doesnt seem to apply to multiple dicts ^^ – Dakota Mac Dylan Carter MacBai Jun 25 '21 at 20:02

2 Answers2

1

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

The answer is: You don't. It looks like you're trying to iterate over the dictionaries, and only retain price information. So, why not make a list of prices?

prices = [d["price"] for d in x]
Paul M.
  • 10,481
  • 2
  • 9
  • 15
1

Use list comprehension and list indices instead to get your price variables

prices = [d['price'] for d in x]
z1 = prices[0]
z2 = prices[1]
# ...etc
chatax
  • 990
  • 3
  • 17