سؤال

I have the following situation:

data = {'key1' : 'value1',
       'key2': [ 
                   {'subkey1': 'subvalue1',
                    'subkey2': 'subvalue2'},

                   {other dictionaries}
                   ...
                ]
        }

I have the exact dictionary:

{'subkey1': 'subvalue1', 'subkey2': 'subvalue2'}

stored in a variable. I would like to remove it from the data dict. How could I do this?

هل كانت مفيدة؟

المحلول

lists have a remove method, so if you know the key

data['key2'].remove({'subkey1': 'subvalue1', 'subkey2': 'subvalue2'})

نصائح أخرى

If you know that it's the first element of the list, you can use the del command to delete the 0 th element of that list.

If you don't know which element in the list it is, you can iterate the list looking for the element you want to delete, or you can use a list comprehension to remove an element.

The pseudo-code for the iteration would go something like:

for each element in the list I want to iterate:
  if this element is the one I want to delete:
    delete(element)

The list comprehension may be something like the following:

dict['key2'] = [i for i in dict['key2'] if i != THE_ELEMENT_YOU_WANT_TO_DELETE]

If you don't know the matching key (here 'key2'), you can use:

exact_dict = {'subkey1': 'subvalue1',
              'subkey2': 'subvalue2'}

for val in data.itervalues():
    try:
        if exact_dict in val:
            val.remove(exact_dict)
    except TypeError:
        pass

Assuming you have only two levels of nesting as given in your example:

for key in data.keys():
  if type(data[key])==type(list()):
    if item_to_del in data[key]:
        data[key].remove(item_to_del)

For deeper level of nesting, expand on this idea of iterating and checking for containment then removing.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top