python - 在列表中的字典中搜索元素

时间:2013-05-08 12:37:27

标签: python

我的数据结构如下:

  - testSet: a list of records in the test set, where each record
             is a dictionary containing values for each attribute

在每条记录中都有一个名为“ID”的元素。我现在想要通过ID值在testSet内搜索记录。因此,当我给出ID = 230时,我想返回记录,它的ID元素等于230.

我该怎么做?

3 个答案:

答案 0 :(得分:5)

next((x for x in testSet if x["ID"] == 230), None)

这将返回带有该ID的第一个项目,如果找不到,则返回None

答案 1 :(得分:2)

这样的东西?

for record in testSet:
    if record['ID'] == 230:
        return record

答案 2 :(得分:0)

E.g:

set = [{'ID': 50}, {'ID': 80}]

def find_set(id):
    return [elem for elem in set if elem['ID'] == id]

这将返回具有指定ID的所有项目。如果您只想要第一个,请添加[0](在检查它是否存在之后,例如:

def find_set(id):
    elems = [elem for elem in set if elem['ID'] == id]
    return elems[0] if elems else None