I have the following Nested Dictionary:
go._Order_Data_DB.items()
Out[62]: dict_items([(84852344, {'_action': 'OPEN', '_type': 0, '_symbol': 'EURUSD', '_price': 0.0, '_SL': 50, '_TP': 50, '_comment': 'DWX_Python_to_MT', '_lots': 0.01, '_magic': 123456, '_ticket': 0}), (84852345, {'_action': 'CLOSE', '_type': 0, '_symbol': 'EURUSD', '_price': 0.0, '_SL': 50, '_TP': 50, '_comment': 'DWX_Python_to_MT', '_lots': 0.01, '_magic': 123456, '_ticket': 84852345}),
(84852374, {'_action': 'OPEN', '_type': 0, '_symbol': 'GBPUSD', '_price': 0.0, '_SL': 50, '_TP': 50, '_comment': 'DWX_Python_to_MT', '_lots': 0.01, '_magic': 123456, '_ticket': 84852345})])
I would like to retrieve the Order Numbers (key) if two conditions are met: '_action' == 'OPEN'
and '_symbol' == ccy
. I tried using the function below but it only looks at the first criteria, would be great if someone knows how to make both criteria work, as it seems to be ignoring the 'and'.
def get_order_num(ccy):
for k, v in go._Order_Data_DB.items():
for k1, v1 in v.items():
if v1 == ccy and v1 == 'OPEN':
return(k)
There are two main issues:
if
statement can query keys from the values of your outer dictionary.return
. To extract all items satisfying your conditions, yield
results instead and then exhaust your generator via list
.Here's a demonstration;
d = dict([(84852344, {'_action': 'OPEN', '_type': 0, '_symbol': 'EURUSD', '_price': 0.0, '_SL': 50, '_TP': 50, '_comment': 'DWX_Python_to_MT', '_lots': 0.01, '_magic': 123456, '_ticket': 0}),
(84852345, {'_action': 'CLOSE', '_type': 0, '_symbol': 'EURUSD', '_price': 0.0, '_SL': 50, '_TP': 50, '_comment': 'DWX_Python_to_MT', '_lots': 0.01, '_magic': 123456, '_ticket': 84852345}),
(84852374, {'_action': 'OPEN', '_type': 0, '_symbol': 'GBPUSD', '_price': 0.0, '_SL': 50, '_TP': 50, '_comment': 'DWX_Python_to_MT', '_lots': 0.01, '_magic': 123456, '_ticket': 84852345})])
def get_order_num(ccy):
for k, v in d.items():
if v['_symbol'] == ccy and v['_action'] == 'OPEN':
yield k
res1 = list(get_order_num('EURUSD')) # [84852344]
res2 = list(get_order_num('GBPUSD')) # [84852374]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments