Home > Blockchain >  How to remove an item from every dict in a list
How to remove an item from every dict in a list

Time:04-06

Sample:

sample = {
    "value1": "foo",
    "value2": "bar",
    "value3": "baz",
    "array": [
        {
            "key1":'value1',
            "key2":'value2',
            "key3":'value3',
        },
        {
            "key1":'value4',
            "key2":'value5',
            "key3":'value6',
        },
        {
            "key1":'value7',
            "key2":'value8',
            "key3":'value9',
        }
          ]
}

I need to delete all key1s and values from all dicts in this array leaving only key2, key3 in each object.

The only thing I can find from google is how to iterate and delete an entire dict in an list, not a single key.

Haven't tried deleting but I did just try to get the other values like this.. couldn't get this either

    domains_list = dict(map(lambda item: (item['key1'], item['key2']), sample['array'].items()))

error: AttributeError: 'list' object has no attribute 'items'

CodePudding user response:

To get You moving: sample['array'] is a list (python type), which doesnt have .items(). So I'd iterate something like for dictionary in sample['array'] and then call dictionary.items().

  • Related