Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing a dictionary from a list of dictionaries in python

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.

like image 921
Naman Sogani Avatar asked Jun 26 '15 08:06

Naman Sogani


2 Answers

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).

like image 92
Dan Gittik Avatar answered Oct 08 '22 20:10

Dan Gittik


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

  • standard dictionaries are unordered, so there is no such thing as a "first" key.
like image 31
Hugues Fontenelle Avatar answered Oct 08 '22 22:10

Hugues Fontenelle