Python Forum

Full Version: KeyError in OrderedDict
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, I'm pretty new to python and would really like some help with a KeyError I'm receiving in the python code. I am using python 3.7.6. The code is:
'value': OrderedDict(sorted([tag['Key'],tag['Value']) for tag in x['Tags']])))
The particular json that I'm using as input is mixed. Some have a Tags attribute and some do not. I am getting the KeyError on the entries that do not have the Tags attribute. I have done some reading on possibly adding a default value if the attribute is missing, but have not found any concrete examples. Can anyone provide an example to either check if the tag attribute is there or provide a default value to the OrderedDict so that it doesn't throw the KeyError? Thanks in advance for your time.
One way is to check existence with 'if x['Tags'] in ...'. Another approach is to use try...except