简体   繁体   中英

Delete an entire dict if matching a Key

I am new to python but still tried to search in internet for solution. But could not find any solution. Here is my data which I would like to trim:

{'Items': [
        {'event': 'active', 'options.target': 'items', 'meta.timestamp': 1584826254819, 'id': 'foo111', 'userId': '1a938ea1-c65e-641a-5db5-5e56c7d8e90b', 'properties.new': 'ABC123'
        },
        {'event': 'active', 'options.target': 'previousTop', 'meta.timestamp': 1584820823598, 'id': 'foo111', 'userId': '1a938ea1-c65e-641a-5db5-5e56c7d8e90b', 'properties.new': 'KUCC00302'
        },
        {'_.from': 'engineEnd', '_.called': 'track', 'event': 'active', 'traits.id': 'foo333', 'options.target': 'items', 'properties.old': 'ABC123', 'meta.timestamp': 1584826518511, 'partner_resid': 'r-1a938ea1-c65e-641a-5db5-5e56c7d8e90b', 'id': 'foo111', 'userId': '1a938ea1-c65e-641a-5db5-5e56c7d8e90b', 'properties.new': 'ABC111', 'id': 'dc3775e0-6bbb-11ea-a789-4f693944a864', 'anonymousId': '3bd5eda3-8625-4b54-b02b-e24f78011ca7', '_.originalAction': 'track', 'type': 'track'}
}

I would like to trim dict having a key properties.old Here is my code which I am failing to filter:

for item in json_result['Items']:
    if 'properties.old' in item:
        del item

Any suggestions on what I am doing wrong?

You could consider creating a new object with list comprehension. Check out this one-liner:

result = { 'Items' : [dic for dic in json_result['Items'] if not 'properties.old' in dic] }

This should work for you (you just needed to iterate through the keys of the internal dictionaries):

for idx, elem in enumerate(json_results['Items']):
    if 'properties.old' in elem.keys():
        del json_results['Items'][idx]
print(json_results)

Outputs:

{'Items': [{'event': 'active', 'options.target': 'items', 'meta.timestamp': 1584826254819, 'id': 'foo111', 'userId': '1a938ea1-c65e-641a-5db5-5e56c7d8e90b', 'properties.new': 'ABC123'}, {'event': 'active', 'options.target': 'previousTop', 'meta.timestamp': 1584820823598, 'id': 'foo111', 'userId': '1a938ea1-c65e-641a-5db5-5e56c7d8e90b', 'properties.new': 'KUCC00302'}]}

Hey you're failling because you're deleting the local item variable in the loop and not the list element. Try iterating over the index and using pop or remove.

        > >>> a=list(range(10))
        > >>> for i in a:       
                  del i    
        > >>> a 
          [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
        > >>>

Get the index first, and do a dry run (print results) before the actual removal:

from pprint import pprint as pp

json_result = {'Items': [{'event': 'active',
                          'options.target': 'items',
                          'meta.timestamp': 1584826254819,
                          'id': 'foo111',
                          'userId': '1a938ea1-c65e-641a-5db5-5e56c7d8e90b',
                          'properties.new': 'ABC123'
                         },
                         {'event': 'active',
                          'options.target': 'previousTop',
                          'meta.timestamp': 1584820823598,
                          'id': 'foo111',
                          'userId': '1a938ea1-c65e-641a-5db5-5e56c7d8e90b',
                          'properties.new': 'KUCC00302'
                         },
                         {'_.from': 'engineEnd',
                          '_.called': 'track',
                          'event': 'active',
                          'traits.id': 'foo333',
                          'options.target': 'items',
                          'properties.old': 'ABC123',
                          'meta.timestamp': 1584826518511,
                          'partner_resid': 'r-1a938ea1-c65e-641a-5db5-5e56c7d8e90b',
                          'id': 'foo111',
                          'userId': '1a938ea1-c65e-641a-5db5-5e56c7d8e90b',
                          'properties.new': 'ABC111',
                          'id': 'dc3775e0-6bbb-11ea-a789-4f693944a864',
                          'anonymousId': '3bd5eda3-8625-4b54-b02b-e24f78011ca7',
                          '_.originalAction': 'track',
                          'type': 'track'
                         }
                        ]
               }

for item in json_result['Items']:
    if 'properties.old' in item:
        # pp(item)
        index = json_result['Items'].index(item)
        remove_item = json_result['Items'][index]
        # pp(remove_item)
        print(json_result['Items'][index]['properties.old'])
        del json_result['Items'][index]

Returning:

ABC123

The value of the dictionary entry where that dict has now been removed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM