简体   繁体   English

如何通过字典中的项目名称获取列表编号?

[英]How to get a list number by a name of an item in a dict?

I have a list with only dicts in it and I want to get the position of the first occurrence of an string (item) in all of the dicts.我有一个只有字典的列表,我想获得所有字典中第一次出现的字符串(项目)的 position。

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
    }
]

I want to get the position of the first occurrence of "type": "buyNow" and later work with the other items in the dict.我想获得第一次出现"type": "buyNow" ,然后再处理字典中的其他项目。

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")

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.如果你想要所有的事件,你可以发出break关键字。

Another way of doing this is:另一种方法是:

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

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.此外,如果您想在示例中专门遍历 A dict 键,例如 (type) 您可以使用条件帮助。

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



output:
signature abc
signature def
signature ghi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM