繁体   English   中英

在列表中查找部分字典元素的索引

[英]Find the index of a partial dictionary element in a list

我有一个字典列表如下:

myList=[{'id':1,'key1':'a','key2':'b'},{'id':8,'key1':'c','key2':'d'}, 
        {'id':6,'key1':'a','key2':'p'}]

要查找元素索引,我目前正在执行以下语句:

print myList.index({'id':8,'key1':'c','key2':'d'})

返回1

但是,我想做这样的事情:

print myList.index({'id':8})

应该返回1

实施起来应该比较简单。 为Python 3编写,在Python 2中你应该使用.iteritems() (不创建临时列表)。

def partial_dict_index(dicts, dict_part):
    for i, current_dict in enumerate(dicts):
        # if this dict has all keys required and the values match
        if all(key in current_dict and current_dict[key] == val 
                for key, val in dict_part.items()):
            return i
    raise ValueError("...")

可以使用更好的名字......

如果您正在寻找单行(而不是可重用的代码),并且您的数据量很小,您可以执行以下操作:

[elem["id"] for elem in myList].index(8)

从每个字典中提取id,然后查找提供的id的索引。 根据您的总体目标和数据集的外观,这可能是也可能不是您想要的......

编辑:请将您接受的答案更改为@ delnan的更正答案,该答案非常相似且可能表现更好。

您可以实现自己的列表。 这是打印第一个找到的结果的示例。 我添加了ValueError来复制.index()的现有行为。

class DictList(list):

    def index(self, obj):
        for i, o in enumerate(self):
            if o['id'] == obj['id']:
                return i
        else:
            raise ValueError('x not in list')


myList = DictList(({'id':1,'key1':'a','key2':'b'},{'id':8,'key1':'c','key2':'d'}, 
                   {'id':6,'key1':'a','key2':'p'}))

>>> print myList.index({'id': 8})
1

>>> print myList.index({'id': 10})
ValueError: x not in list

暂无
暂无

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

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