How do I find the index of items structure

Question:

How do I find the index of items in this structure using python?

[{'symbol':'ETHUSD'} , {'symbol':'BTCUSD'}]
Asked By: ruffone

||

Answers:

As you did not provide any details at all, here is a simple solution.

l = [{'symbol':'ETHUSD'} , {'symbol':'BTCUSD'}]
target = "BTCUSD"

for index, element in enumerate(l):
    if element["symbol"] == target:
        print(index)
Answered By: Itération 122442

Explanation

You have a list [ ]

Inside of the list you have 2 dictionaries { }

Each dictionary contains a key and value pair.


Lists

You can view items in a list by their index value

Let’s take this simpler code to start with.

list = ['apple','oranges','grapes']

Just keep in mind, the index begins with 0

So to access grapes you can do the following:

print(list[2])

Output: grapes


Dictionaries

Dictionaries are stored as {"KEY":"VALUE"} pairs

You access the value, using the KEY.

For example:

my_dict = {'name':'kaleb'}

to find the VALUE of ‘name’ you use the KEY

print(my_dict['name'])

Output: kaleb


Now back to your code

Remember, you have a list that contains 2 dictionaries

list = [{'symbol':'ETHUSD'} , {'symbol':'BTCUSD'}]

So say for example you wanted to access BTCUSD

To do so you first need to access the second item in the list, which has an index of 1. Remember index begins with 0

list[1]

This gets you to the second dictionary in the list, now you access the BTCUSD VALUE using the KEY

['symbol']

Putting it all together you get

value = list[1]['symbol']
print(value)

Output: BTCUSD

Answered By: Kaleb Fenley
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.