0

I have this result:

{'orderId': 1234567, 'price': '20.5', 'qty': '125', 'status': 'open'}
{'orderId': 7654321, 'price': '15.5', 'qty': '15', 'status': 'open'}
{'orderId': 9876543, 'price': '32.0', 'qty': '102', 'status': 'open'}

I want to assign each orderID to individual variable, so I can do something to each of them.

Above result is gained thru filtering code as follow:

orders = product.get_open_orders(product='sample')

keys = ['orderId', 'price', 'qty', 'status']
res = [{k: d[k] for k in keys} for d in orders]

for status in res:
    if status['status'] == 'open':
        print(status)
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
carlg32
  • 5
  • 3
  • 1
    Can you show some example of what you want to do with them? So far I don't see why `status['orderId']` would not be enough. – Norrius Jul 08 '18 at 08:51
  • Could you elaborate on your desired output format?! – Cleb Jul 08 '18 at 08:54
  • @Norrius Yes, i can get all orderId with status['orderId']. The results are now showing all numbers. I want to extract each orderId number and assign to variable, like orderId1=1234567. I am using python wrapper, such that to cancel order, I need to key in the orderId. – carlg32 Jul 08 '18 at 08:59
  • @Cleb Output format is orderId1=1234567 , orderId2=7654321 , orderId3=9876543. This is after assigning each orderId to respective variable. – carlg32 Jul 08 '18 at 09:13
  • You can check [this question](https://stackoverflow.com/q/5036700/1534017) – Cleb Jul 08 '18 at 09:21

2 Answers2

0

Just do status['orderId']

count = 1
for status in res:
    if status['status'] == 'open':
        print(status)
        orderId = status['orderId']
        eval("orderId"+str(count) + "=" + "orderId")

This will create orderId0, orderId1 ...

vizsatiz
  • 1,933
  • 1
  • 17
  • 36
  • Yes, I got this result:1234567 7654321 9876543. I want to be able to extract this individually to assign to variable like (orderId1=1234567 , orderId2=7654321 , orderId3=9876543). – carlg32 Jul 08 '18 at 09:08
  • Why dont you try using eval. I will edit the above code – vizsatiz Jul 08 '18 at 10:03
  • Pls edit above code to show how I can capture all the orderId and placing them to variables. Not familiar yet with eval() function usage. – carlg32 Jul 08 '18 at 14:11
0

If you want a sequence of enumerated items, the correct data structure for that is a list:

orders = []
for status in res:
    if status['status'] == 'open':
        orders.append(status['orderId'])
print(orders)  # [1234567, 7654321, 9876543]
print(orders[0], orders[2])  # 1234567 9876543

Or, in more idiomatic Python:

orders = [status['orderId'] for status in res if status['status'] == 'open']
print(orders)  # [1234567, 7654321, 9876543]
Norrius
  • 7,558
  • 5
  • 40
  • 49