Barbiyong Barbiyong - 1 year ago 35
Python Question

How to find the index number of list that in dictionary?

The example list

'date': array(['06/08/2016', '06/09/2016', '06/10/2016']),
'close': array([ 923.13, 914.25, 909.42])

I try to get the Date of close is 914.25 that is list['date'][2]
but i don't know how to get index 2 for close.

Thank you.

Answer Source

Ideally, if you would do this kind of queries often, you should restructure your data to fit the use case better. For instance, have a dictionary where the keys are amounts and dates are values. Then, you would have quick O(1) lookups into the dictionary by key.

But, in this state of the problem, you can solve it with zip() and next():

>>> d = {
... 'date': ['06/08/2016', '06/09/2016', '06/10/2016'],
... 'close': [ 923.13,  914.25,  909.42]
... }
>>> a = 914.25
>>> next(date for date, amount in zip(d['date'], d['close']) if amount == a)

Note that if the amount would not be found, next() would fail with a StopIteration exception. You can either handle it, or you can provide a default beforehand:

>>> a = 10.00
>>> next((date for date, amount in zip(d['date'], d['close']) if amount == a), 'Not Found')
'Not Found'