Let’s say I pull JSON daily and after some initial indexing, what I have looks like this:
[{'CategoryId': 493, 'name': 'foo'},
{'CategoryId': 735, 'name': 'bar'},
{'CategoryId': 988, 'name': 'baz'},
{'CategoryId': 1024, 'name': 'foo_foo'},
{'CategoryId': 729, 'name': 'foo_bar'},
{'CategoryId': 743,
'name': 'foo_baz',
...}
]
And I want to access the dict where name is foo_baz.
Here is what I do now (ignore the [...] as they are just initial indexing I do to get to this point and is besides the point of the question):
(json.loads(response.text)[...][...][5])
Now this works… most of the time. Occasionally, there will be additional CategoryId that screws up my indexing, like so:
[{'CategoryId': 493, 'name': 'foo'},
{'CategoryId': 735, 'name': 'bar'},
{'CategoryId': 988, 'name': 'baz'},
{'CategoryId': 1024, 'name': 'foo_foo'},
{'CategoryId': 729, 'name': 'foo_bar'},
{'CategoryId': 522, 'name': 'new_cat'},
{'CategoryId': 743,
'name': 'foo_baz',
...}
]
This now ruins my indexing thanks to new_cat. What I have been doing is just implementing a try except, but this becomes un-pythonic very quickly:
try:
lists = (json.loads(response.text)[...][...][5])
except KeyError:
lists = (json.loads(response.text)[...][...][6])
...
So, my question is, is there a way I can just index this json based on the value of name? something like:
(json.loads(response.text)[...][...][function where name is equal to 'foo_baz'])
>Solution :
If you need to do multiple lookups, I recommend:
lookup = {d['name']: d['CategoryId'] for d in data}
Now you can do lookup['foo_baz']. And if there’s really more data you haven’t shown us, you can store the whole dict:
lookup = {d['name']: d for d in data}
Now you can do lookup['foo_baz']['CategoryId'].