Home > database >  How to get a list number by a name of an item in a dict
How to get a list number by a name of an item in a dict

Time:03-27

I have a list with only Dicts in it and I want to get the position by the first occurance of an string (item) in all of the Dicts

The list in question:

[
    {
        "signature": "abc",
        "type": "list",
        "source": "v2",
        "price": 2
    },
    {
        "signature": "def",
        "type": "buyNow",
        "source": "v2",
        "price": 3
    },
    {
        "signature": "ghi",
        "type": "buyNow",
        "source": "v2",
        "price": 10
    }
]

and I want to get the position of the firt occurance of "type": "buyNow" and later work with the other items in the Dict

CodePudding user response:

You can do this by:

for i in list_name:
    if i['type'] == 'buyNow':
        #Do whatever you want with the dictionary
        break #Exits the for loop because you only want the first occurrence.

You can emit the break keyword if you want all the occurrences.

Another way of doing this is:

next(index for index, dict in enumerate(list_name) if dict['type'] == 'buyNow'))

CodePudding user response:

What you want to do is to search in a list

def get_type(type_value):
    return next(elem for elem in you_list if elem["type"] == type_value, None)

get_type("buyNow")

CodePudding user response:

you can try this. moreover, if you want to specifically iterate over A dict key like (type) in your example you can use the conditionals help.

for i in dic:
for j in i:
    print(j,list(i.values())[0])
    break



output:
signature abc
signature def
signature ghi
  • Related