I get this error message, when I try to parse the result set, returned by MATCH query. What I want is to somehow convert the resultset to a dictionary. I should say that I know how to access particular fields of the result set - like row['a']['name'], but what I do not like is that I can not convert the whole row['a'] to a dictionary or to get something like row['a'].keys().
So, this is what I tried:
res = graph.cypher.execute("MATCH (a:Object {id: 1}) return a")
for r in res:
print r['a']['id'] # this works
for r in res:
print r['a'].keys() # this does not
#what I want is something like
{x:y for (x,y) in zip(r['a'].keys(), r['a'].values()}
From the documentation, it looks like execute is returning a py2neo.cypher.RecordList of py2neo.cypher.Record objects, which can then be iterated over:
for r in res:
for v in r['a']:
# do something with v
Unfortunately, looking at the source code, there doesn't seem to be an obvious way to access the column name, without doing a dir(r) and filtering the results, e.g. [c for c in dir(r) if not c.startswith('_')].
Edit: Looking at it again, I guess r is the Record while r['a'] is something else. You'll have to see what kinda of object r['a'] is using type(r['a']), and then see if there's a way to access the keys.
The accessors directly attached to the Node object are a shortcut to the properties attribute. Therefore you will want to iterate through r["a"].properties in the same way you would any other dictionary.
Related
So I am struggling with getting a value from a JSON response. Looking in other post I have managed to write this code but when I try to search for the key (character_id) that I want in the dictionary python says that the key doesn't exist. My solution consists in getting the JSON object from the response, converting it into a string with json.dumps() and the converting it into a dictionary with json.loads(). Then I try to get 'character_id' from the dictionary but it doesn't exist. I am guessing it is related with the format of the dictionary but I have little to none experience in python. The code that makes the query and tries to get the values is this: (dataRequest is a fuction that makes the request and return the response from the api)
characterName = sys.argv[1];
response = dataRequest('http://census.daybreakgames.com/s:888/get/ps2:v2/character/?name.first_lower=' + characterName + '&c:show=character_id')
jsonString = json.dumps(response.json())
print(jsonString)
dic = json.loads(jsonString)
print(dic)
if 'character_id' in dic:
print(dic['character_id'])
The output of the code is:
{"character_list": [{"character_id": "5428662532301799649"}], "returned": 1}
{'character_list': [{'character_id': '5428662532301799649'}], 'returned': 1}
Welcome #Prieto! From what I can see, you probably don't need to serialize/de-serialize the JSON -- response.json() returns a python dictionary object already.
The issue is that you are looking for the 'character_id' key at the top-level of the dictionary, when it seems to be embedded inside another dictionary, that is inside a list. Try something like this:
#...omitted code
for char_obj in dic["character_list"]:
if "character_id" in char_obj:
print(char_obj["character_id"])
if your dic is like {"character_list": [{"character_id": "5428662532301799649"}], "returned": 1}
you get the value of character_id by
print(dic['character_list'][0][character_id])
The problem here is that you're trying to access a dictionary where the key is actually character_list.
What you need to do is to access the character_list value and iterate over or filter the character_id you want.
Like this:
print(jsonString)
dic = json.loads(jsonString)
print(dic)
character_information = dic['character_list'][0] # we access the character list and assume it is the first value
print(character_information["character_id"]) # this is your character id
The way I see it, the only hiccup with the code is this :
if 'character_id' in dic:
print(dic['character_id'])
The problem is that, the JSON file actually consists of actually 2 dictionaries , first is the main one, which has two keys, character_list and returned. There is a second sub-dictionary inside the array, which is the value for the key character_list.
So, what your code should actually look like is something like this:
for i in dic["character_list"]:
print(i["character_id"])
On a side-note, it will help to look at JSON file in this way :
{
"character_list": [
{
"character_id": "5428662532301799649"
}
],
"returned": 1
}
,where, elements enclosed in curly-brackets'{}' imply they are in a dictionary, whereas elements enclosed in curly-brackets'[]' imply they are in a list
I have this kind of dictionary:
{"Odds":{"Home-Win": {"Name-BookMaker":{A:value}}}
This structure is saved inside my pickle and I want to access the element called value, with the for loop iterate over the pickle:
for match in name_of_the_pickle:
odds = match.get("Odds")
home_win = odds.get("Home-Win").values()
but with this last instruction my output is the following:
"dict_values([{A:value}])"
But what I want is only "value", how can I do this?
Ok I found a working example for te instance you gave us based on casting the dict_values object to a list:
odds = match.get("Odds")
home_win = list(odds.get("Home-Win").values())[0]
At this point home_win looks like this:
{'A': 'value'}
Then to retrieve 'value', you could call values() again:
val = list(home_win.values())[0]
print(val)
>>>'value'
I successfully imported from the web this json file, which looks like:
[{"h_mag":"19.7","i_deg":"9.65","moid_au":"0.035"},{"h_mag":"20.5","i_deg":"14.52","moid_au":"0.028"},
etc ...
I want to extract the values of the key moid_au, later compare moid_au with the key values of h_mag.
This works: print(data[1]['moid_au']), but if I try to ask all the elements of the list it won't, I tried: print(data[:]['moid_au']).
I tried iterators and a lambda function but still has not work yet, mostly because I'm new in data manipulation. It works when I have one dictionary, not with a list of dictionaries.
Thanks in advance for other tips. Some links were confusing.
Sounds like you are using lambda wrong because you need map as well:
c = [{"h_mag":"19.7","i_deg":"9.65","moid_au":"0.035"},{"h_mag":"20.5","i_deg":"14.52","moid_au":"0.028"}]
list(map(lambda rec: rec.get('moid_au'), c))
['0.035', '0.028']
Each lambda grabs a record from your list and you map your function to that.
Using print(data[:]['moid_au']) equals to print(data['moid_au']), and you can see that it won't work, as data has no key named 'moid_au'.
Try working with a loop:
for item in data:
print(item['moid_au'])
using your approach to iterate over the whole array to get all the instances of a key,this method might work for you
a = [data[i]['moid_au']for i in range(len(data))]
print(a)
In which exact way do you want to compare them?
Would it be useful getting the values in a way like this?
list_of_dicts = [{"h_mag":"19.7","i_deg":"9.65","moid_au":"0.035"}, {"h_mag":"20.5","i_deg":"14.52","moid_au":"0.028"}]
mod_au_values = [d["moid_au"] for d in list_of_dicts]
h_mag_values = [d["h_mag"] for d in list_of_dicts]
for key, value in my_list.items ():
print key
print value
for value in my_list.values ():
print value
for key in my_list.keys():
print key
I have a dictionary like such:
dict = {'x':[2,6,4],'y':[56,5,1]}
I would like to pass one of these lists into the query method:
new_df = df.query('col3 == #dict["x"]')
But I get a UndefinedVariableError. Is there any way to do what I want without the roundabout step of setting a new variable and then using "#" with that one
new_v = dict['x']
new_df = df.query('col3 == #new_v')
Do you definetly need the query function?
Otherwise following the example in the query docs you could try something like:
df.loc[df['col3'].isin(dict['x'])]
Note that the isin, might be required since your dictionary returns a list
So you want something like ?
df.query('col3=={}'.format(dict['x']))
In Python, to find all attributes, there is:
dir(object)
object.__dict__.keys()
But what i want is to list what is in the second branch, not only the first branch, it's kind of a recursive operation?
How to do that?
it's like
dir(dir(x) for x in dir(math))
tried this and still get the same result duplicated:
>>> for i in dir(math):
... for j in i:
... print dir(j)
and all results are the methods of str
Update: it seems that the dir() commande returns a list of str, here is a simple hack; I tried to exclude the reserved names to see if i go further, but the result was only str
[i for i in dir(math) if i[0]!="_"]
[type(i) for i in dir(math) if i[0]!="_"]
Thank you again :)
object.__dict__.keys() # Just keys
object.__dict__.values() # Just values
object.__dict__.items() # Key-value pairs
Edit wait! I think I misunderstood. You want to list an object's properties, and those properties' properties and so on and so forth? Try something like this:
def discover(object):
for key in dir(object):
value = getattr(object, key)
print key, value
discover(value)
It's pretty crude, but that's the recursion I think you're looking for. Note that you will have to stop it manually at some point. There's no turtles at the bottom, it goes on and on.