Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
KeyError in OrderedDict
#1
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.
Reply
#2
One way is to check existence with 'if x['Tags'] in ...'. Another approach is to use try...except
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to escape OrderedDict as an argument? Mark17 2 1,990 Dec-23-2020, 06:47 PM
Last Post: Mark17
  extracting second values elements only in every keys in an OrderedDict glennford49 4 2,470 Nov-12-2020, 08:22 AM
Last Post: glennford49
  AttributeError: 'collections.OrderedDict' object has no attribute 'value_counts Kristenl2784 4 7,268 Jul-17-2020, 01:50 AM
Last Post: palladium
  collections.OrderedDict Bert123456 2 1,748 Jul-09-2020, 08:51 PM
Last Post: Bert123456
  Iterating list of oredereddict for creating new list of ordereddict babypython 7 3,640 May-05-2019, 05:32 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020