How To Avoid Error On Missing Keys When Using Dict Comprehension
How do I ignore missing keys in a pd.DataFrame.from_dict comprehension iteration? @jezrael kindly answered my problem on making a df with dictionary values here: https://stackoverf
Solution 1:
The link's OK - it's in Stackoverflow and isn't going anywhere.
Meet the dict.get
method. By way of a pre-amble, this is almost everything you need to know about it:
>>>d = {'present': 'real_value'}>>>d.get('present')
'real_value'
>>>d.get('absent') isNone
True
>>>d.get('absent', 'default')
'default'
You should find that the modified comprehension
{k: dict(v['fees']) for k, v in d.items() if v.get('fees') is not None}
serves your needs, but this is untested code. Possibly more readable is
{k: dict(v['fees']) for k, v in d.items() if 'fees' in v}
Solution 2:
There's a couple different ways to solve this.
One way is to use a try
except
statement to catch the error.
Another way is to test is the key is in the dict key in dict
.
Another would be to use the dict's get method dict.get(key, default = None)
where the default option will return None if the value is not found or you can set it to want you need.
Post a Comment for "How To Avoid Error On Missing Keys When Using Dict Comprehension"