Barbiyong Barbiyong - 5 months ago 10
Python Question

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

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'][1]
but i don't know how to get index 1 for close.

Thank you.


Here is the solution from @alecxe


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


Sorry for my word and grammar, English is not my primary language.

Thanks for every user for advising me.

Answer

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)
'06/09/2016'

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'
Comments