Python 在字典列表中提取字典子集,直到找到特定键为止

Python 在字典列表中提取字典子集,直到找到特定键为止,python,dictionary,Python,Dictionary,我有一张单子 dict = [{'a':'1'},{'b':'2'},{'c':'3'},{'Stop':'appending'},{'d':'4'},{'e':'5'},{'f':'6'}] dict1 = [{'a':'1'},{'b':'2'},{'c':'3'},{'d':'4'},{'Stop':'appending'},{'e':'5'},{'f':'6'}] 我想提取所有列表元素,直到找到键“Stop”并将其附加到新字典 预期产出: new_dict = [{'a':'1'},

我有一张单子

dict = [{'a':'1'},{'b':'2'},{'c':'3'},{'Stop':'appending'},{'d':'4'},{'e':'5'},{'f':'6'}]

dict1 = [{'a':'1'},{'b':'2'},{'c':'3'},{'d':'4'},{'Stop':'appending'},{'e':'5'},{'f':'6'}]
我想提取所有列表元素,直到找到键“Stop”并将其附加到新字典

预期产出:

new_dict = [{'a':'1'},{'b':'2'},{'c':'3'}]

new_dict1 = [{'a':'1'},{'b':'2'},{'c':'3'},{'d':'4'}]
代码:

您可以使用enumerate获取与键停止匹配的元素的索引,然后在其上使用列表切片:

dic = [{'a':'1'},{'b':'2'},{'c':'3'},{'Stop':'appending'},{'d':'4'},{'e':'5'},{'f':'6'}]
index = next(index for index, elt in enumerate(dic) if elt.get('Stop'))
new_dic = dic[0:index]  # [{'a': '1'}, {'b': '2'}, {'c': '3'}]
另外,不要对对象名称使用dict关键字,以避免隐藏内置原语

更新:如果您只想使用键Stop跳过该元素并使用所有其他元素,则将上述切片操作更新为:

new_dic = dic[0:index] + dic[index+1:] # [{'a': '1'}, {'b': '2'}, {'c': '3'}, {'d': '4'}, {'e': '5'}, {'f': '6'}]

首先找到像键一样具有“Stop”的元素的索引,然后将列表切片到这些索引的第一个

尝试:


另外,我认为您应该为列表选择更好的名称,尤其是第一个,dict在python中是一个保留字。

它已经在标准库中了

import itertools

dict1 = [{'a':'1'},{'b':'2'},{'c':'3'},{'d':'4'},{'Stop':'appending'},{'e':'5'},{'f':'6'}]

res = list(itertools.takewhile(lambda x: "Stop" not in x, dict1))

print(res)

输出:

[{'a': '1'}, {'b': '2'}, {'c': '3'}, {'d': '4'}]

键“Stop”内的值可以将dictionary更改为dictionary..@AnandThirtha,您可以使用enumerate、list Comprehensive和next的组合来获取具有键“Stop”的元素的索引,然后使用切片来获得结果。请看我更新的答案。@Manuel我不知道。我不知道如何查找副本。我依靠那些在标签中是SME的人能够为基本问题找到好的副本。假设这是一个基本问题tools.takes这是在'stop'之后附加所有元素,还可以编写一个函数,在DICT列表中查找'stop'键的索引,然后使用索引X对列表进行切片您的问题是什么?你的代码有问题吗?字典不是无序的吗?我不能硬编码“appending”值,因为它可能会随dict的不同而变化。看看编辑,我对此进行了更新。这个答案缺少教育性的解释。@mickmackusa也许这是一个重复的问题,应该是一个重复的问题,因为这确实是基本情况,但我无法在合理的时间内找到类似的东西。我不认为这个片段是无法解释的,它很简单。不用担心。我真的很感激你打猎。没有足够的人这样做。干杯
import itertools

dict1 = [{'a':'1'},{'b':'2'},{'c':'3'},{'d':'4'},{'Stop':'appending'},{'e':'5'},{'f':'6'}]

res = list(itertools.takewhile(lambda x: "Stop" not in x, dict1))

print(res)

[{'a': '1'}, {'b': '2'}, {'c': '3'}, {'d': '4'}]