Christian
Christian

Reputation: 605

How can I replace "None" as a dictionary value with an empty dictionary?

Im parsing a complex json string and am working with nested dictionaries and some nested dic.get() functions in my class.

Instead of receiving a None when a higher level key doesn't exist, I would like to find an empty dictionary so that my code (dict.get()) keeps working.

Right now I would like to replace all dictionary values named None with an empty dictionary {}, but I didn't find any good solution how to do it.

So basically I want this:

{'a': {},
 'b': 'Text',
 'c': 5,
 'd': {'d1': {}}

but sadly have that:

{'a': None,
 'b': 'Text',
 'c': 5,
 'd': {'d1': None}

Upvotes: 4

Views: 3790

Answers (2)

mujjiga
mujjiga

Reputation: 16926

You can use the default value for the get method

dict.get("a", {})

Sample:

d = { 'b' : 1,
       'c' : { 'd': 2 } }
print (d.get('a', {}))
print (d.get('c', {}).get('a', {}))
print (d.get('x', {}).get('y', {}).get('z', {}))

output:

{}
{}
{}

Upvotes: 2

Andrej Kesely
Andrej Kesely

Reputation: 195633

Other solution is to traverse the dictionary recursively and replace the None values:

def replace(d):
    if isinstance(d, dict):
        for k in d:
            if d[k] is None:
                d[k] = {}
            else:
                replace(d[k])
    elif isinstance(d, list):
        for v in d:
            replace(v)


d = {'a': None,
     'b': 'Text',
     'c': 5,
     'd': {'d1': None}}

replace(d)
print(d)

Prints:

{'a': {}, 'b': 'Text', 'c': 5, 'd': {'d1': {}}}

Upvotes: 6

Related Questions