V Manikandan
V Manikandan

Reputation: 370

Handling KeyError recursively

I would like to set the the key value as '-' recursively for the key which causes the KeyError.

This is my dictionary

Rojar = {
    '2010': {'fcf_share': '96.87', 'roce': '10.52', 'roic': '0', 'roe': '19.95', 
    'roa': '2.6'},
    '2011': {'fcf_share': '30.43', 'roce': '9.94', 'roic': '0', 'roe': 
    '26.48', 'roa': '2.76'}, 
    '2012': {'fcf_share': '75.54', 'roce': '11.84', 'roic': 
    '0', 'roe': '27.84', 'roa': '3.25'},
        }

Like Rojar more than 500 people having the data but not all having every field. I want to take 'roce', 'roe', and 'roa' fields corresponding to every year from everyone. By parsing the person code to the function I can take the values from

Rojar = {k: {'roce': v['roce'], 'roe':v['roe'],'roa':v['roa']} for k, v in Rojar.iteritems()}

#it returns
    Rojar = {
    '2010': {'roce': '10.52','roe': '19.95', 'roa': '2.6'},
    '2011': {'roce': '9.94','roe': '26.48', 'roa': '2.76'}, 
    '2012': {'roce': '11.84','roe': '27.84', 'roa': '3.25'},
            }

But the problem is everyone may not have those values. for example, if Rojan does not have 'roce' corresponds to year '2010' and 'roa' corresponds to year '2012'

#it has to return like 

    Rojar = {
    '2010': {'roce': '-','roe': '19.95', 'roa': '2.6'},
    '2011': {'roce': '9.94','roe': '26.48', 'roa': '2.76'}, 
    '2012': {'roce': '11.84','roe': '27.84', 'roa': '-'},
            }

thanks

Upvotes: 0

Views: 362

Answers (1)

isedev
isedev

Reputation: 19601

Use the dict.get method:

Rojar = {k: {'roce': v.get('roce','-'),
             'roe': v.get('roe','-'),
             'roa': v.get('roa','-')}
        for k, v in Rojar.iteritems()}

That way, if the dictionary v does not have a given key, the value will default to '-'.

Upvotes: 3

Related Questions