So I have a list of dictionaries, where each dictionary has two key-value pairs. Something like
l1 = [{'key1':'value1','key2':'value2'},
{'key1':'value1','key2':'value2'},
...
]
Now what I want is to remove a dictionary from this list just be checking first key
and its value
. I can check whether a whole dictionary is present in the list and then remove it. But I just want to check whether a dictionary with a particular first key
is present or not in the list. Such a dictionary will be unique. And I want to remove that dictionary from this list subsequently. How do I do that?
Edit: While removing, I have only one key-value pair. So I want to remove the dictionary using one pair only. If I had both the pairs then I could have done
l1.remove({'key1':'value1', 'key2':'value2'})
But this is not the case as I do not have another pair. That's why I said that dictionary is unique.
Given,
ds = [{'key1': 'value1', 'key2': 'value2'},
{'key1', 'value3', 'key2', 'value4'},
...]
You can remove a dictionary with a unique key-value using a list comprehension:
ds = [d for d in ds if d['key1'] != 'value1']
But then you are traversing the entire list, creating a new list without that dictionary, and not capturing the dictionary. You can also do this manually:
for i, d in enumerate(ds):
if d['key1'] == 'value1':
d1 = ds.pop(i)
break
In which case you only traverse what you must, don't create a new list, and capture the dictionary. However, if you really care about performance (and don't care about order), I would suggest grouping the dictionaries by their unique key value to begin with:
ds = {'value1': {'key1': 'value1', 'key2': 'value2'},
'value3': {'key1', 'value3', 'key2', 'value4'},
...}
Because ds['value1']
is O(1) (immediate), whereas any traversal is O(n) (has to go over the entire list in the worst case).
Don't call your lists list
!
Use list comprehension.
key-value pair
To remove list elements when a particular key-value pair is present:
l1 = [{'key1':'value1','key2':'value2'},
{'key1':'value3','key2':'value4'}]
l2 = [element for element in l1 if element.get('key1', '') != 'value1']
(Notice the get
method with a default return value).
key present
To remove list elements when a particular key is present:
l2 = [element for element in l1 if 'key1' in element]
Remarks
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With