Python Forum
KeyError in OrderedDict - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: KeyError in OrderedDict (/thread-25470.html)



KeyError in OrderedDict - rberna - Mar-31-2020

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.


RE: KeyError in OrderedDict - perfringo - Apr-01-2020

One way is to check existence with 'if x['Tags'] in ...'. Another approach is to use try...except