1

I have a tuple of dicts in form:

mylist = ({'a': 'a0',  't': 't0'}, {'a': 'a1',  't': 't1'}, {'a': 'a2',  't': 't2'}, ...)

How can I remove a dict in the for loop? I tried the following but at the end doc is still in the tuple:

for doc in mylist:
    if doc['a']=="a0":
        del doc
timgeb
  • 76,762
  • 20
  • 123
  • 145
NargesooTv
  • 837
  • 9
  • 15

2 Answers2

5

First of all, don't use the name list, you will shadow the built in list.

Tuples are immutable, so you have to build a new tuple.

>>> t = ({'a': 'a0',  't': 't0'}, {'a': 'a1',  't': 't1'}, {'a': 'a2',  't': 't2'})
>>> tuple(d for d in t if d['a'] != 'a0')
({'a': 'a1', 't': 't1'}, {'a': 'a2', 't': 't2'})

This assumes all your dictionaries actually have the key 'a'. If that does not have to be the case, feel free to add some error checking code or use the get method of the dictionary with a fallback value in the generator expression.

timgeb
  • 76,762
  • 20
  • 123
  • 145
3

To start with; you have defined a Tuple, not a List. The primary difference between the two is that Tuples are immutable. This means if you want to modify your collection, you will need to use a List:

my_list = [{'a': 'a0',  't': 't0'}, {'a': 'a1',  't': 't1'}, {'a': 'a2',  't': 't2'}]

Note the use of square brackets, rather than round.

With that knowledge, you can either choose to:

Build another Tuple, omitting the values you wish to remove:

my_tuple = ({'a': 'a0',  't': 't0'}, {'a': 'a1',  't': 't1'}, {'a': 'a2',  't': 't2'})
my_new_tuple = tuple(item for item in my_tuple if item['a'] != 'a0') 

Or, use a List, and remove the values you don't want:

my_list = [{'a': 'a0',  't': 't0'}, {'a': 'a1',  't': 't1'}, {'a': 'a2',  't': 't2'}]  
for item in my_list:
    if item['a'] == 'a0':
        my_list.remove(item)
NixonInnes
  • 340
  • 1
  • 3
  • 10