Reputation: 122
I am new here, this is my first question. We all start somewhere :D
I have this data being returned to me via an API and I store it in a variable named jsonResponseData
{
"date-value": [{
"dateTime": "2020-06-25",
"value": "34365"
}, {
"dateTime": "2020-06-26",
"value": "7268"
}, {
"dateTime": "2020-06-27",
"value": "4762"
}, {
"dateTime": "2020-06-28",
"value": "4650"
}, {
"dateTime": "2020-06-29",
"value": "2934"
}, {
"dateTime": "2020-06-30",
"value": "4973"
}, {
"dateTime": "2020-07-01",
"value": "3594"
}, {
"dateTime": "2020-07-02",
"value": "19674"
}]
}
Is this even a nested dictionary? I am fairly new to programming and any help is welcome!
Regardless of what it is, how would I parse it so I only keep the 7 value
values and am able to then add them up into one number.
Upvotes: 3
Views: 299
Reputation: 17
You can use this function which will return the sum of the values. Hope this helps!
def getValuesSum(json_data):
values_list=[int(items['value']) for items in json_data['date-value']]
return sum(values_list)
Upvotes: 2
Reputation: 524
Is this even a nested dictionary?
Sort of. It's a dictionary with a list of dictionaries inside it.
Regardless of what it is, how would I parse it so I only keep the 7 value values and am able to then add them up into one number.
Try this:
import json
data = """
{
"date-value": [{
"dateTime": "2020-06-25",
"value": "34365"
}, {
"dateTime": "2020-06-26",
"value": "7268"
}, {
"dateTime": "2020-06-27",
"value": "4762"
}, {
"dateTime": "2020-06-28",
"value": "4650"
}, {
"dateTime": "2020-06-29",
"value": "2934"
}, {
"dateTime": "2020-06-30",
"value": "4973"
}, {
"dateTime": "2020-07-01",
"value": "3594"
}, {
"dateTime": "2020-07-02",
"value": "19674"
}]
}
"""
data_dict = json.loads(data)
values = 0
for x in data_dict["date-value"]:
values += int(x['value'])
print(values)
That should result in values being the sum of all 7 numbers.
Upvotes: 1
Reputation: 5232
Yes, this is a nested dictionary. Instead of using a loop, you can use list comprehension.
>>> sum(int([inner['value']) for inner in my_dict['date-value']])
82220
For each nested dictionary in my_dict, turn the 'value' element into an integer and sum the results.
Upvotes: 2
Reputation: 351
values = [x["value"] for x in jsonResponseData["date-value"]]
List Comprehension
Upvotes: 2
Reputation: 712
This is one way to extract those values (given that the object above is called dict
).
for val in dict["date-value"]:
print(val["value"])
Upvotes: 1
Reputation: 1299
You can iterate through the list, and access the dict inside.
for entry in data['date-value']:
print(entry['value'])
# or whatever else you want to do with the values
Upvotes: 3