0

I have a JSON object as follows:

{u'2015-05-11': 2, u'2015-05-04': 1}

Here the dates can vary, i.e., I can query for multiple dates.

I want to extract the numbers in the object and add them. So in this example I want to extract 2 and 1 and them up to get the result 3.

Another example:

{u'2015-05-11': 6, u'2015-05-04': 0}

Here the answer will be 6 + 0 = 6.

Another example of the JSON object with multiple dates:

{u'2015-04-27': 0, u'2015-05-11': 2, u'2015-05-04': 1}

Here the answer will be: 0 + 2 + 1 = 3

I want to loop through the JSON object and extract all the numbers. I've read the answers provided here and here. The problem is the, the JSON object that I have does not have a fixed key that I can query.

How do I go about this?

Community
  • 1
  • 1
praxmon
  • 5,009
  • 22
  • 74
  • 121

3 Answers3

4

These are all Python dicts, not JSON objects.

Since you don't seem to care about the keys at all, you can just get the values and sum them:

result = sum(data.values())
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

If you are sure it's a json data, the data is like as below:

'{"2015-05-11": 2, "2015-05-04": 1}'

Convert json to dict:

data = json.loads(a)
# {u'2015-05-11': 2, u'2015-05-04': 1}

According to your question, solve the problem.

result = sum(data.values())
# 3
Burger King
  • 2,945
  • 3
  • 20
  • 45
-2

Daniel's answer provides you the solution youre looking for but you should also know that you can iterate through a Python dict with enumerate.

for value, key in enumerate(your_dict):
    print value, key
Luc Kim-Hall
  • 178
  • 1
  • 4