Barbiyong
Barbiyong

Reputation: 147

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.

Upvotes: 1

Views: 71

Answers (3)

totoro
totoro

Reputation: 2456

Where is the example from? I don't think you can have an array of strings in Python.

Assuming that the Python data structure is:

{
    'date': ['06/08/2016', '06/09/2016', '06/10/2016'],
    'close': [923.13,  914.25,  909.42]
}

and the indexes of close always matches the indexes of date, then:

In [1]: d = {
   ...:     'date': ['06/08/2016', '06/09/2016', '06/10/2016'],
   ...:     'close': [923.13,  914.25,  909.42]
   ...: }

You find the index of 914.25:

In [2]: d['close'].index(914.25)
Out[2]: 1

You find the corresponding date:

In [3]: d['date'][1]
Out[4]: '06/09/2016'

Upvotes: 0

3kt
3kt

Reputation: 2553

You can try this :

>>> data = { 'date': ['06/08/2016', '06/09/2016', '06/10/2016'],'close': [ 923.13,  914.25,  909.42]}
>>> data['date'][data['close'].index(914.25)]
'06/09/2016'

Thanks to index(), you are able to get the index of the required value (914.25 in this case).

Upvotes: 1

alecxe
alecxe

Reputation: 473833

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'

Upvotes: 2

Related Questions