Home > Net >  KeyError when trying to search through list of dictionaries in JSON
KeyError when trying to search through list of dictionaries in JSON

Time:10-04

Im trying to search for a dict key in a JSON file which looks like this:

[{"1.0": {"name": "Name", "message": "Message"}}, 
 {"69.0": {"name": "F.Z", "message": "Dggl"}}
]

I am using :

def main(id:float):
   for i in output_json:
     if(i["id"]==id):
         return(i["message"],i["name"])

to search through the JSON file but it gives me a key error over 'id'. I want the output to be the contents of the dictionary whose key I have inputted.

CodePudding user response:

There's no id key in your dictionaries. The numbers are the keys of the first level of dictionaries, so you need to test if it exists as a key, which you can do with in.

You need to convert id to a string, since the keys of your dictionaries are strings, not floats.

def main(id: float):
    key = str(id)
    for d in output_json:
        if key in d:
            return d[key]['message'], d[key]['name']
  • Related