JSON Object parsing: Loop through dynamic data - python

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?

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())

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

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

Related

How to start from second key when iterating over dictionary using for loop in Python

I am computing returns from data in a dictionary. My keys are dates and for every key I have a dataframe with data to compute my returns. To compute the returns I need data today and yesterday (t and t-1), hence I want to initiate from the second observation (key).
Since I do not have much experience my initial thought was to execute like this:
dict_return = {}
for t, value in dict_data.items()[1:]:
returns = 'formula'
dict_returns[t] = returns
Which gave me the error:
TypeError: 'dict_items' object is not subscriptable
Searching for an answer, the only discussion I could find was skipping the first item, e.g. like this:
from itertools import islice
for key, value in islice(largeSet.items(), 1, None):
Is there a simple approach to skip the first key?
Thank you
If you are in Python 3 you need to use a list, Dict_ items ([‘No surfacing ‘,’flippers’]) returns a dict_ The items object is no longer of the list type and does not support index, this is why the list type can be used
I can think of 2 options, both require an extra step:
Option 1: Create a second dict without your key and loop over that
loop_dict = dict_data.pop(<key_to_remove>)
Then loop over loop_dict as you have done above.
Option 2: Create a list of keys from your dict and loop over that
keys = dict_data.keys()
loop_keys = keys[1:]
for key in loop_keys:
Etc
If you pass a reference to your dictionary to list() you will get a list of the dictionary's keys. This is because dictionaries are iterable. In your code you're not interested in the key's value so:
dict_data = {'a': 1, 'b': 2} # or whatever
dict_data[list(dict_data)[1]] = 3
print(dict_data)
Output:
{'a': 1, 'b': 3}

Getting data from a dictionary Python

I'm using python dictionaries from counting the repeated objects from an array.
I use a function obtained from this forum from counting the objects, and the obtained result is on the next format: {object: nºelements, ...).
My issue is that the function doesn't return the dictionary objects differentiated by keys and I don't know how to get the objects.
count_assistence_issues = {x:list(assistances_issues).count(x) for x in list(assistances_issues)}
count_positive_issues = {x:list(positive_issues).count(x) for x in list(positive_issues)}
count_negative_issues = {x:list(negative_issues).count(x) for x in list(negative_issues)}
print(count_assistence_issues)
print(count_positive_issues)
print(count_negative_issues)
This is the output obtained:
{school.issue(10,): 1, school.issue(13,): 1}
{school.issue(12,): 1}
{school.issue(14,): 2}
And this is the output I need to obtain:
{{issue: school.issue(10,), count: 1},
{issue: school.issue(13,), count: 1}}
{{issue: school.issue(12,), count: 1}}
{{issue: school.issue(14,), count: 2}}
Anyone know how to differenciate by keys the elements of the array using the function?
Or any other function for counting the repeated objects for obtaining a dictionary with the format {'issue': issue,'count': count)
Thanks for reading!
Given your input and output. I would consider the following.
1) Merge all your counts into a single dictionary
#assuming that what diffrentitaes your issues is a unique ID/key/value etc.
#meaning that no issues are subsets of the other. IF they are this will need some tweaking
issue_count = {}
issue_count.update(count_assistence_issues)
issue_count.update(count_positive_issues)
issue_count.update(count_positive_issues)
Getting the counts is then simply:
issue_count[school.issue(n,)]
The key is your array. If you want an alternative. You could make a list of keys or dict of your keys. You can make this as verbose as you want.
key_issues = {"issue1":school.issue(1,),"issue2":school.issue(2,)....}
This then allows you to call your counts by:
issue_count[key_issues["issue1"]]
If you want to use the "count" field. You would need to fix your counter to give you a dict of your issue with field count but that's another question.

Python:Get value of a dictionary present in aTuple

I have a tuple like: t= ({'count': 5L},)
Here i don't want to use for loop but want to get value as 5.Then how can i do it?
I tried with coverting to string then using JSON.
import json
s = str(t)
d = json.loads(s)
I got error:ValueError: No JSON object could be decoded
And winded up with no result.
I want to get the value of count as integer 5 & store in a variable.
Anyone having any idea?
No need to use Json since it is already your tuple is already a Python data structure.
If you know the index of the item in the tuple, and you know the keyname you can access it directly using:
t = ({'count': 5L},)
value = int(t[0]['count'])

Urlencode dictionary using Python - naming key and value in the url

I am attempting to generate a URL link in the following format using urllib and urlencode.
<img src=page.psp?KEY=%28SpecA%2CSpecB%29&VALUE=1&KEY=%28SpecA%2C%28SpecB%2CSpecC%29%29&VALUE=2>
I'm trying to use data from my dictionary to input into the urllib.urlencode() function however, I need to get it into a format where the keys and values have a variable name, like below. So the keys from my dictionary will = NODE and values will = VALUE.
wanted = urllib.urlencode( [("KEY",v1),("VALUE",v2)] )
req.write( "<a href=page.psp?%s>" % (s) );
The problem I am having is that I want the URL as above and instead I am getting what is below, rather than KEY=(SpecA,SpecB) NODE=1, KEY=(SpecA,SpecB,SpecC) NODE=2 which is what I want.
KEY=%28SpecA%2CSpecB%29%2C%28%28SpecA%2CSpecB%29%2CSpecC%29&VALUE=1%2C2
So far I have extracted keys and values from the dictionary, extracted into tuples, lists, strings and also tried dict.items() but it hasn't helped much as I still can't get it to go into the format I want. Also I am doing this using Python server pages which is why I keep having to print things as a string due to constant string errors. This is part of what I have so far:
k = (str(dict))
ver1 = dict.keys()
ver2 = dict.values()
new = urllib.urlencode(function)
f = urllib.urlopen("page.psp?%s" % new)
I am wondering what I need to change in terms of extracting values from the dictionary/converting them to different formats in order to get the output I want? Any help would be appreciated and I can add more of my code (as messy as it has become) if need be. Thanks.
This should give you the format you want:
data = {
'(SpecA,SpecB)': 1,
'(SpecA,SpecB,SpecC)': 2,
}
params = []
for k,v in data.iteritems():
params.append(('KEY', k))
params.append(('VALUE', v))
new = urllib.urlencode(params)
Note that the KEY/VALUE pairings may not be the order you want, given that dicts are unordered.

Parse json data

My data.json is
{"a":[{"b":{"c":{ "foo1":1, "foo2":2, "foo3":3, "foo4":4}}}],"d":[{"e":{"bar1":1, "bar2":2, "bar3":3, "bar4":4}}]}
I am able to list both key/pair values. My code is:
#! /usr/bin/python
import json
from pprint import pprint
with open('data2.json') as data_file:
data = json.load(data_file)
pprint(data["d"][0]["e"])
Which gives me:
{u'bar1': 1, u'bar2': 2, u'bar3': 3, u'bar4': 4}
But I want to display only the keys without any quotes and u like this:
bar1, bar2, bar3, bar4
Can anybody suggest anything? It need not be only in python, can be in shell script also.
The keys of this object are instances of the unicode string class. Given this, the default printing behavior of the dict instance for which they are the keys will print them as you show in your post.
This is because the dict implementation of representing its contents as a string (__repr__ and/or __str__) seeks to show you what objects reside in the dict, not what the string representation of those objects looks like. This is an important distinction, for example:
In [86]: print u'hi'
hi
In [87]: x = u'hi'
In [88]: x
Out[88]: u'hi'
In [89]: print x
hi
This should work for you, assuming that printing the keys together as a comma-separated unicode is fine:
print ", ".join(data["d"][0]["e"])
You can achieve this using the keys member function from dict too, but it's not strictly necessary.
print ', '.join((data["d"][0]["e"].keys()))
data["d"][0]["e"] returns a dict. In python2, You could use this to get the keys of that dict with something like this:
k = data["d"][0]["e"].keys()
print(", ".join(k))
In python3, wrap k in a list like this
k = list(data["d"][0]["e"].keys())
print(", ".join(k))
Even simpler, join will iterate over the keys of the dict.
print(", ".join(data["d"][0]["e"]))
Thanks to #thefourtheye for pointing this out.

Categories

Resources