0

I have a list of key-value pair in python. A sample of this list is:

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

Now I have a string str1 and what I want to do is to match it with text field of each key-value pair and delete the one which matches. So if my string is Zen then delete {'text': 'Zen', 'value': 'Zen'} from the list.

I tried to do del list_pairs[str1] but it throws error as list indices can only be integers and not str.

How can I delete the items from my list of key-value pair?

user2916886
  • 847
  • 2
  • 16
  • 35
  • You have a `list` with `dict` objects. You need to use integer indices to access the `list` items, or iterate over it directly `for d in list_pairs: ...` then you can index into the `dict` objects with strings, i.e. `d['text'] == 'Zen'`. – juanpa.arrivillaga Feb 23 '18 at 18:52
  • You have a list of dicts NOT "key-value" pairs, there's a difference – smac89 Feb 23 '18 at 19:26

3 Answers3

4

True @smac89. Concise answer would be :

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

Thanks @ juanpa.arrivillaga

Not recommend incorrect version:

str1 = 'Zen'
for d in list_pairs:
    if d['text'] == str1:
        list_pairs.remove(d)
skmth
  • 164
  • 6
1

Delete

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)

out:

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

List comprehension

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)

out:

[{}, {'text': 'Global', 'value': 'Global'}, {'text': 'Corporation', 'value': 'Corporation'}]
PythonProgrammi
  • 22,305
  • 3
  • 41
  • 34
0
def del_match(str):
     for index,item in enumerate(list_pairs):
         if item['text'] is str:
             del list_pairs[index]

I am leaving this bad answer here, please refer to the comments below on why it is a bad answer, may be it will help people to get more out of this problem.

Aparna Chaganti
  • 599
  • 2
  • 5
  • 15