Home > Mobile >  Dictionary that doesn't exist returning name of string, how to skip this Python
Dictionary that doesn't exist returning name of string, how to skip this Python

Time:04-21

I have a dictionary that holds different value and id's. The first index in the dictionary does not hold the 'id' dictionary, but the second index does The problem I am having is when I print:

return[0]['values']['id']

It returns 'id'

Because there is no such dictionary in the first index

The second index return[1]['values']['id'] The 'id' dictionary does exist so returns [{"id": "4651234", "type":"instant"}]

I'm trying to create a list of only the id values that exist, how do I get it to skip the all the indexes where the 'id' dictionary does not exist? Rather than stop the program and print the string 'id'.

CodePudding user response:

You can just loop and use a if statement to check if the id exists or not :

id_list = []
for key in return:
    if return[key]['values']['id'] != 'id':
        id_list.append(return[key]['values']['id'])

(Btw you should avoid naming your variables with name like return or any other keyword that can have a signification for the language)

CodePudding user response:

you can if the returned value it is a list or a string

if isinstance(return[0]['values']['id'],list):
   #process the data
elif isinstance(return[0]['values']['id'],str):
   #do nothing

Having said that, a couple of recommendations: I assume that you wrote it as an example but, just in case, is not possible to have "return" as the name of the variable since it is a reserved word.

Another point is that if the same call returns different things (i.e. the first returns a str, the second a list with a dictionary in it, etc), it may be an indication that the data needs some cleaning before trying to access it. Otherwise you may end up with nasty results and you won't know where they are coming from.

  • Related