Reputation: 605
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
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
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