i'm new with python and can't get the inner content of the the dictionary.
i have a "detail" as a dictionary and i would like to pull data from "properties" so i will have "time" and "distinct_id" as keys
Right now the keys in the dictionary are "event" and "properties" and would like to go deeper in the dictionary
example of dictionary "details":
{"event":"User Profile - Page View","properties":{"time":1428969601,"distinct_id":"14cb3d99b195-0feaf7b1c-5c267370-c0000-14cb3d99b1a220"}}
Thanks!
Each dictionary (instance of dict) comes with a method __getitem__(self, index), for which [] is a syntactic suggar. In order to access an unnested dictionary, you would normally use details['event'].
Since nested dictionary is just another dictionary, the same applies further: details['properties']['time'] will return the 'time' of nested dictionary.
If you want the code to be a bit nicer, you can assign the first dictionary to a variable
properties = details['properties']
and access the attributes as you would in normal (not nested) dictionary
print properties['time']
print properties['distinct_id']
dict = {"event":"User Profile - Page View","properties":{"time":1428969601,"distinct_id":"14cb3d99b195-0feaf7b1c-5c267370-c0000-14cb3d99b1a220"}}
dict['properties']['time']
Related
I want to send below json format through patch on session,but don't know how to create it in Robot Framework.
Normal patch I can use create dictionary to handle.
But have no idea about nested JSON.
{
"Boot": {
"Boot_Order": [
"device_1",
"device_2"
]
}
}
Below is part of my test case:
${select}= CREATE LIST device_1 device_2
${combine_body} = CREATE DICTIONARY Boot={} Boot_Order=${select}
Thanks!
Your current script outputs a dictionary with two keys and their own values like
{ "Boot": "{}", "Boot_Order": ["device_1", "device_2"] }
To achieve a nested dictionary, you'd need to create first the inner dictionary and then assign that inner dictionary under some key to the outer dictionary. Consider following:
${select}= Create List device_1 device_2
${inner_dict}= Create Dictionary Boot_Order=${select}
${outer_dict}= Create Dictionary Boot=${inner_dict}
This would have an output you are looking for
{ "Boot": {"Boot_Order": ["device_1", "device_2"]}}
If you have a lot of complexity in the JSON outputs and you can template the content, it might make sense to look also into the JSON Library for Robot Framework.
I am a python rookie and so my question is simple (yet I couldn't find the answer here):
I need to access values in my dictionary (named 'database') but without knowing the actual values. So lets say I want to print the first value of the dictionary whatever it is. I found this:
print(database.values()[0].keys()[0])
Which seems to be what I'm looking for but when running the script I get this error:
TypeError: 'database' object does not support indexing
Can you please help?
You might want to check out Ordered Dict:
As others mentioned in the comments, you would get the elements in no particular order because dictionaries are unordered.
This sample code works:
from collections import OrderedDict
database = OrderedDict()
database = {
"key1": {"key10": "value10", "key11": "value11"},
"key2": {"key20": "value20", "key21": "value21"}
}
If you want to print out or access all first dictionary keys in database.values() list, you may use something like this:
for key, value in database.items():
print value.keys()[0]
If you want to just access first key of the first item in database.values(), this may be useful:
print database.values()[0].keys()[0]
Hope this helps.
{
"card_quota": 0,
"custom_data": "{\"child_name\":\"홍설\",\"uid\":\"29\",\"lid\":\"56\",\"count\":\"1\",\"schedule\":\"2016-06-18(토)\"}",
"escrow": false
}
This is dictionary type of python. I konw to get value using a code like temp['card_quata']. But i want to know using key in ['custom_data'] getting value like child_name or uid .. How can i do that?
You can parse custom_data with json.loads and then access the returned dict:
>>> import json
>>> json.loads(temp['custom_data'])['child_name']
'홍설'
Note that the example data you provided is not valid Python since Python uses False instead of false.
You can simply get the values of any dictionary using the keys. So lets take it step by step:
first, lets get the dictionary -
temp['custom_data']
will give you the child dictionary, then, in order to access the items of this child dict, you can use the child keys:
temp['custom_data']['child_name']
temp['custom_data']['uid']
etc.
I'm using Python and "requests" to practice the use of API. I've had success with basic requests and parsing, but having difficulty with list comprehension for a more complex project.
I requested from a server and got a dictionary. From there, I used:
participant_search = (match1_request['participantIdentities'])
To convert the values of the participantIdentities key to get the following data:
[{'player':
{'summonerName': 'Crescent Bladex',
'matchHistoryUri': '/v1/stats/player_history/NA1/226413119',
'summonerId': 63523774,
'profileIcon': 870},
'participantId': 1},
My goal here is to combine the summonerId and participantId to one list. Which is easy normally, but the order of ParticipantIdentities is randomized. So the player I want information on will sometimes be 1st on the list, and other times third.
So I can't use the var = list[0] like how I would normally do.
I have access to summonerId, so I'm thinking I can search the list the summonerId, then somehow collect all the information around it. For instance, if I knew 63523774 then I could find the key for it. From here, is it possible to find the parent list of the key?
Any guidance would be appreciated.
Edit (Clarification):
Here's the data I'm working with: http://pastebin.com/spHk8VP0
At line 1691 is where participant the nested dictionary 'participantIdentities' is. From here, there are 10 dictionaries. These 10 dictionaries include two nested dictionaries, "player" and "participantId".
My goal is to search these 10 dictionaries for the one dictionary that has the summonerId. The summonerId is something I already know before I make this request to the server.
So I'm looking for some sort of "search" method, that goes beyond "true/false". A search method that, if a value is found within an object, the entire dictionary (key:value) is given.
Not sure if I properly understood you, but would this work?
for i in range(len(match1_request['participantIdentities'])):
if(match1_request['participantIdentities'][i]['summonerid'] == '63523774':
# do whatever you want with it.
i becomes the index you're searching for.
ds = match1_request['participantIdentities']
result_ = [d for d in ds if d["player"]["summonerId"] == 12345]
result = result_[0] if result_ else {}
See if it works for you.
You can use a dict comprehension to build a dict wich uses summonerIds as keys:
players_list = response['participantIdentities']
{p['player']['summonerId']: p['participantId'] for p in players_list}
I think what you are asking for is: "How do I get the stats for a given a summoner?"
You'll need a mapping of participantId to summonerId.
For example, would it be helpful to know this?
summoner[1] = 63523774
summoner[2] = 44610089
...
If so, then:
# This is probably what you are asking for:
summoner = {ident['participantId']: ident['player']['summonerId']
for ident in match1_request['participantIdentities']}
# Then you can do this:
summoner_stats = {summoner[p['participantId']]: p['stats']
for p in match1_request['participants']}
# And to lookup a particular summoner's stats:
print summoner_stats[44610089]
(ref: raw data you pasted)
I am originally a c guy but recently I started doing some stuff in python.
The things that gives me trouble is the more advanced data structures in python.
I could do it all with multiple list like in c but that would just be boring right?
anyway here I have a data structure which is basically a list of dicts where the value field of the dict is another list of 2 key-value pairs:
clients = [
{'client1':[{'test':'testvalue','status':'statusvalue'}]},
{'client2':[{'test':'testvalue','status':'statusvalue'}]},
{'client3':[{'test':'testvalue','status':'statusvalue'}]}
]
now I want to be able to acces the testvalue and statusvalue fields and modify or read them. based on the position in the list.
in pseudocode it would be something like:
for i in range(0,clients):
getvalue(clients[i].'test')
setvalue(clients[i].'test')
getvalue(clients[i].'status')
setvalue(clients[i].'status')
in the end I want to use this data structure to render a html page with jinja2
For a start, in Python you should (almost) never iterate over range(len(something)). You iterate over something.
Secondly, your data structure is wrong. There's no point having a list of dicts, each dict containing a single key/value pair and each value consisting of a list with a single item. You should just have a dict of dicts: you can still iterate over it.
clients = {
'client1':{'test':'testvalue','status':'statusvalue'},
'client2':{'test':'testvalue','status':'statusvalue'},
'client3':{'test':'testvalue','status':'statusvalue'},
}
for key, value in clients.iteritems():
print value['test']
value['test'] = 'newvalue'
I have noticed that you put a dictionary inside a list as the value for each client.
I think you may wish to re-configure your data structure as such:
clients = [
{'client1':{'test':'testvalue','status':'statusvalue'}}
{'client2':{'test':'testvalue','status':'statusvalue'}}
{'client3':{'test':'testvalue','status':'statusvalue'}}
]
Therefore, you can begin iterating as such:
for client in clients:
for k, v in client.iteritems(): #this unpacks client into 'client' (k) and {'val'...} (v)
print v['test'] #this gets the value of test.
v['test'] = 'some_new_value' #this sets the value of test.