How to get value using key in python multi dictionary - python

{
"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.

Related

how to access values in a dictionary in python without knowing the actual values?

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.

Parsing JSON in Python (Reverse dictionary search)

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)

Extract python objects from a string

I have files with data looking like
{u'session_id': u'6a208c8cfada4048b26ea7811cbac20f'}
That is, key value pairs and arrays of objects with key value pairs which are of the form u'key' : u'value'
More specifically, the files I see look like what one gets after calling json.loads()on a JSON file.
I want to some how get the data present in these files as python objects or at least valid JSON format (some thing like reverse of json.loads()) so that I can do something like obj['session_id'] and get "6a208c8cfada4048b26ea7811cbac20f".
Thanks in advance
You can use literal_eval from the ast module, which is better than using eval directly:
>>> ast.literal_eval("{u'session_id': u'6a208c8cfada4048b26ea7811cbac20f'}")['session_id']
u'6a208c8cfada4048b26ea7811cbac20f'
>>> z = ast.literal_eval("{u'session_id': u'6a208c8cfada4048b26ea7811cbac20f'}")
>>> isinstance(z, dict)
True

Parse JSON in python to a dictionary

A bit lost after much research. My code below parses the JSON to a dictionary I have thought using json load
response = json.load(MSW) # -->Will take a JSON String & Turn it into a python dict
Using the iteration below I return a series like this which is fine
{u'swell': {u'components': {u'primary': {u'direction': 222.5}}}}
{u'swell': {u'components': {u'primary': {u'direction': 221.94}}}}
ourResult = response
for rs in ourResult:
print rs
But how oh how do I access the 222.5 value. The above appears to just be one long string eg response[1] and not a dictionary structure at all.
In short all I need is the numerical value (which I assume is a part of that sting) so I can test conditions in the rest of my code. Is is a dictionary? With thanks as new and lost
You have to use python syntax as follows:
>>> print response['swell']['components']['primary']['direction']
222.5
Just access the nested dictionaries, unwrapping each layer with an additional key:
for rs in ourResult:
print rs['components']['primary']['direction']

ConfigParser Get Key on given Value

Using ConfigParser I can read value of key easily as shown in the example below-
#config.cfg
[NODE]
192.168.31.22 = node22
192.168.31.23 = node23
192.168.31.26 = node26
#PYTHON CODE
config = ConfigParser.RawConfigParser()
config.readfp(open("config.cfg"))
print config.get("NODE", "192.168.31.22")
>>>node22
Sometime it is required that I read "key" based on given value.
Is there any built-in function to get KEY based on the given VALUE or any workaround for this ?
print config.FUNCTIONXYZ("NODE", "node22")
>>>192.168.31.22
Thank you.
No, there is no direct way. Internally, ConfigParser reads the configuration file into a nested dictionary, and in each sections keys are mapped to values, not the other way around. Frankly, I'm not sure why you want this, but I suspect it's not a common request :)
Implementing your own is very easy, however:
# items in section 'NODE': key, value pairs
for key, value in config.items('NODE'):
if value == WHAT_I_NEED:
print key
If you need many such lookups on a large configuration, consider placing items into a dict first.

Categories