如何从 python 中的键值对列表中删除项目

how to delete item from a list of key-value pairs in python

我在 python 中有 listkey-value 对。此列表的示例是:

list_pairs = [{'text': 'Zen', 'value': 'Zen'}, {'text': 'Global', 'value': 'Global'}, {'text': 'Corporation', 'value': 'Corporation'}]

现在我有一个字符串 str1,我想做的是将它与每个 key-value 对的 text 字段匹配并删除匹配的那个。因此,如果我的字符串是 Zen,则从列表中删除 {'text': 'Zen', 'value': 'Zen'}

我尝试执行 del list_pairs[str1] 但它抛出错误 list indices can only be integers and not str

如何从我的键值对列表中删除项目?

对@smac89。 简洁的答案是:

new_list_pair = [d for d in list_pairs if d['text'] != str1]

感谢@juanpa.arrivillaga

不推荐不正确的版本:

str1 = 'Zen'
for d in list_pairs:
    if d['text'] == str1:
        list_pairs.remove(d)
def del_match(str):
     for index,item in enumerate(list_pairs):
         if item['text'] is str:
             del list_pairs[index]

我在这里留下这个错误的答案,请参阅下面的评论了解为什么它是一个错误的答案,这可能会帮助人们从这个问题中得到更多。

删除

l = [{'text': 'Zen', 'value': 'Zen'}, {'text': 'Global', 'value': 'Global'}, {'text': 'Corporation', 'value': 'Corporation'}]

collect = []
for n, d in enumerate(l):
    for k in d:
        if d[k] == 'Zen':
            print(k)
            collect.append([n, k])

for v in collect:
    del l[v[0]][v[1]]

print(l)

输出:

text
value
[{}, {'text': 'Global', 'value': 'Global'}, {'text': 'Corporation', 'value': 'Corporation'}]

列表理解

l = [{'text': 'Zen', 'value': 'Zen'}, {'text': 'Global', 'value': 'Global'}, {'text': 'Corporation', 'value': 'Corporation'}]

collect = []
[[collect.append([n, k]) for k in d if d[k] == "Zen"] for n, d in enumerate(l)]

for v in collect:
    del l[v[0]][v[1]]

print(l)

输出:

[{}, {'text': 'Global', 'value': 'Global'}, {'text': 'Corporation', 'value': 'Corporation'}]