Kanhaiya Choudhary
Kanhaiya Choudhary

Reputation: 516

Remove keys from python dictionary of dictionary based on some conditions

How can I remove keys from python dictionary of dictionaries based on some conditions?

Example dictionary:

a = { 
  'k': 'abc',
  'r': 20,
  'c': { 
         'd': 'pppq',
         'e': 22,
         'g': 75
  },
  'f': ''}

I want to remove all entries whose values are type of string. It can contain dictionary for any key. Nested key value pairs should also be handled.

Upvotes: 2

Views: 183

Answers (2)

JanLikar
JanLikar

Reputation: 1306

Something like this should work:

def remove_strings(a):
    no_strings = {}

    for k,v in a.items():
        if type(x) is str:
            continue
        elif type(x) is dict:
            no_strings[k] = remove_strings(v)
        else:
            no_strings[k] = v

This function is recursive - it calls itself to process nested dictionaries.

It should be possible to remove the keys in-place (without copying the dictionary), but the code would be a bit less readable that way.

Upvotes: 0

Dani Mesejo
Dani Mesejo

Reputation: 61910

You could do:

a = {
    'k': 'abc',
    'r': 20,
    'c': {
        'd': 'pppq',
        'e': 22,
        'g': 75
    },
    'f': ''}


def remove_string_values(d):
    result = {}
    for k, v in d.items():
        if not isinstance(v, str):
            result[k] = remove_string_values(v) if isinstance(v, dict) else v
    return result


res = remove_string_values(a)
print(res)

Output

{'r': 20, 'c': {'e': 22, 'g': 75}}

Upvotes: 2

Related Questions