the python program that i am writing calls to an api that returns this json:
Code Output
How do i access the subdetails? When i run the .keys() it only lists those three top levels. I want to be able to get specific items, e.g. "Utility"
I've tried several solutions but none parse correctly. I have tried calling the list inside the dictionary, to no avail. Originally i thought it was a dictionary inside of a dictionary, but Python thinks its a list nested into a dictionary.
Any help would be appreciated!
keys() function only returns the keys of dictionary, so it you call keys(), it will only return the three result. The "subdetails" you are referring to are the values of those keys. For key "SUMMARY" as an example, its value is a list instead of dict (note the "[" after the key). However, the list only has a single element. This is quite common in json. To retrive "Utility", all you need to do is data['SUMMARY'][0]['Utility']
Maybe to help you understand the data structure better, call the "values()" and "items()" function to see what it returns.
Since it's a dict of lists of dicts, simply use an index of 0 to access the first item of the list if there is always only one item in each list. For example, if your JSON object is stored as variable data, then the value of Utility can be accessed with data['SUMMARY'][0]['Utility'].
Related
When trying to iterate through a defaultdict my variables were read as strings when they should be read as lists, however, when I changed my code a little bit, it worked but I don't know exactly why. My defaultdict is a dictonary that has a list of dictionaries inside it. The code looked like that
for engagement in engagement_by_account:
for engagement in engagement:
engagement['total_minutes_visited'] = float(engagement['total_minutes_visited'])
And the error was:
TypeError: string indices must be integers
However, when I changed the code to this:
for key,engagement in engagement_by_account.items():
for engagement in engagement:
engagement['total_minutes_visited'] = float(engagement['total_minutes_visited'])
there were no errors anymore.
By default, when you iterate over a dictionary (or defaultdict), you will iterate over the keys of that dictionary. It seems here that you wanted to iterate over the values so you could either do what you did or something like:
for engagements in engagement_by_account.values():
for engagement in engagements:
engagement['total_minutes_visited'] = float(engagement['total_minutes_visited'])
I have received a json file from an api and want to convert it from to a dictionary to a list in python. I already have it loaded as a python dictionary, so I'm really just looking to iterate over it and convert from a dictionary to a list. However, the dictionary has nested lists and not every object within the json file's many objects is always structured the same (i.e. the api will not always return the same json object for every event). I want to convert the dictionary to 3 separate lists, each list for a specific key:value pair I am parsing for.
I've tried using KeyError in a try/except statement to account for cases where there is no value but haven't had much luck. Also tried importing defaultdict from collections to no success as well. I gather I should be able to make the rests of my lists once I get some help with this first one. Hopefully I didn't overcomplicate the question
data = load_json()# function responsible for loading the json from a stored file
new_list = []
for some_key1 in data
if new_list['some_key1'] > 0:
try:
new_list.append(['some_key1'], some_key1)
except:
new_list.get(['some_key1'], '0')
for x in range(len(new_list)):
print(new_list[x])
I am looking to make one list for storing each object's (i.e. each python 'breaking' dictionary) key:value pair where some_key1 exists (i.e. this means in this case I will have a list for aDifferentCherry and yetAnotherDifferentCherry.
This answer tells me that json starting with "[" is a list/array. Suffice to say, can several lists with dictionaries inside be considered valid json? As in [{"test": "test"}][{"test":"test"}] ?
I have some data returning that seems to be in this format but when I try and render the data inside a json viewer, it tells me it's the incorrect format. So maybe these viewers don't like json that's returned as a dictionary inside a list.
I'm not entirely sure if the data is in multiple lists but if I print "data[0] and then data1 then data[2] etc, it returns different dictionaries, so I assume it is a list. I would ideally like to loop through all the data so I could use a python for loop and say data[i] to go through all lists, but I suppose I would need to know what I am looping through.
From your example [{"test": "test"}][{"test":"test"}] you actually have two different lists. And each list has a dictionary within it.
JSON parsers expect to parse one entity, so you need to put those two lists within a larger list. Like this:
[ [{"test": "test"}], [{"test":"test"}] ]
I know it is easy to implement.
I want a dictionary like class, which takes a list of dictionaries in the constructor.
If you read from this dict by key, the dict-class should check the list of dictionaries and return the first value. If none contains this key KeyError should be thrown like a normal dict.
This dictionary container should be read only for my usage.
You seem to be describing collections.ChainMap, which will be in the next version of Python (3.3, expected to go final later this year). For current/earlier versions of Python, you can copy the implementation from the collections source code.
Not really answer to the question: what if you just define method that merge all dictionaries into one? Why make new class for it?
How to merge: How to merge two Python dictionaries in a single expression?
Varargs: Can a variable number of arguments be passed to a function?
You can easily implement this with this logic.
Iterate over all the dictionaries in the list.
For each dictionary, see if it has the required key by using key in value statement.
If value is found, return the value from the function.
If you have iterated over all dictionaries, and value is not found, Raise KeyError exception.
I have a Dictionary of Classes where the classes hold attributes that are lists of strings.
I made this function to find out the max number of items are in one of those lists for a particular person.
def find_max_var_amt(some_person) #pass in a patient id number, get back their max number of variables for a type of variable
max_vars=0
for key, value in patients[some_person].__dict__.items():
challenger=len(value)
if max_vars < challenger:
max_vars= challenger
return max_vars
What I want to do is rewrite it so that I do not have to use the .iteritems() function. This find_max_var_amt function works fine as is, but I am converting my code from using a dictionary to be a database using the dbm module, so typical dictionary functions will no longer work for me even though the syntax for assigning and accessing the key:value pairs will be the same. Thanks for your help!
Since dbm doesn't let you iterate over the values directly, you can iterate over the keys. To do so, you could modify your for loop to look like
for key in patients[some_person].__dict__:
value = patients[some_person].__dict__[key]
# then continue as before
I think a bigger issue, though, will be the fact that dbm only stores strings. So you won't be able to store the list directly in the database; you'll have to store a string representation of it. And that means that when you try to compute the length of the list, it won't be as simple as len(value); you'll have to develop some code to figure out the length of the list based on whatever string representation you use. It could just be as simple as len(the_string.split(',')), just be aware that you have to do it.
By the way, your existing function could be rewritten using a generator, like so:
def find_max_var_amt(some_person):
return max(len(value) for value in patients[some_person].__dict__.itervalues())
and if you did it that way, the change to iterating over keys would look like
def find_max_var_amt(some_person):
dct = patients[some_person].__dict__
return max(len(dct[key]) for key in dct)