How to iterate over attribute names of an custom object - python

Hi I have a JSON Object in my python code and I use them as object in my code. Its type is JSONHelper.X which is a custom class I wrote which reads a json file and transform its to a object for using easily.
{
"Gui":{
"Images":{
"Logo1":"url1",
"Logo2":"url2",
"Logo3":"url3",
"Logo4":"url4",
"Logo5":"url5"
}
}
}
How can I retrive pair of attribute name and value from this object to give another class as parameter. JSONHelper object does not seem to have dict attribute so I can not say Gui.Images.keys(). When I print Gui.Images I only get values.
I can reach attribute names as below. Is there any better way to do this?
def prop_names(self):
l = []
public_props = (name for name in dir(self.settings.Images) if not name.startswith('_'))
for name in public_props:
if name is not "count" and name is not "index":
print(name)
print(l
)
output:
Logo1
Logo2
Logo3
Logo4
Logo5

Convert your JSON helper string into dictionary using json.load (see comments from Barmar). From there you can access the keys values that you want.
import json
import itertools
j="""{
"Gui":{
"Images":{
"Logo1":"url1",
"Logo2":"url2",
"Logo3":"url3",
"Logo4":"url4",
"Logo5":"url5"
}
}
}"""
d = json.loads(j)
l = [list(d[k1][k2].keys()) for k1 in d.keys() for k2 in d[k1].keys()]
print(list(itertools.chain.from_iterable(l)))
Result:
['Logo1', 'Logo2', 'Logo3', 'Logo4', 'Logo5']

Related

Extracting multiple values from a JSON Object

I have a JSON object that looks as such, stored in a variabled called results:
{
"users":[
{
"pk":54297756964,
"username":"zach_nga_test",
"full_name":"",
"is_private":false,
"profile_pic_url":"https://instagram.fcxl1-1.fna.fbcdn.net/v/t51.2885-19/44884218_345707102882519_2446069589734326272_n.jpg?efg=eyJybWQiOiJpZ19hbmRyb2lkX21vYmlsZV9uZXR3b3JrX3N0YWNrX2JhY2t0ZXN0X3YyNDI6Y29udHJvbCJ9&_nc_ht=instagram.fcxl1-1.fna.fbcdn.net&_nc_cat=1&_nc_ohc=bdMav5vmkj0AX9lHIND&edm=ALdCaaIBAAAA&ccb=7-5&ig_cache_key=YW5vbnltb3VzX3Byb2ZpbGVfcGlj.2-ccb7-5&oh=00_AT9BXADjYsi8BkryuLhynAbrTCGmgjucZ6CJUxW4VS49QA&oe=62D6BC4F&_nc_sid=bfcd0c",
"is_verified":false,
"has_anonymous_profile_picture":true,
"has_highlight_reels":false,
"account_badges":[
],
"latest_reel_media":0
},
{
"pk":182625349,
"username":"joesmith123",
"full_name":"Joe Smith",
"is_private":false,
"profile_pic_url":"https://scontent-lga3-1.cdninstagram.com/v/t51.2885-19/264887407_23285995fef5595973_2438487768932865121_n.jpg?stp=dst-jpg_s150x150&_nc_ht=scontent-lga3-1.cdninstagram.com&_nc_cat=105&_nc_ohc=8YpjD2OKeoEAX_gXrh3&edm=APQMUHMBAAAA&ccb=7-5&oh=00_AT9UuhNl9LL_ANffkCcyNNFPv5_yK7J2FKQpRPmqEIri3w&oe=62D60038&_nc_sid=e5d0a6",
"profile_pic_id":"2725348120205619717_182625349",
"is_verified":false,
"has_anonymous_profile_picture":false,
"has_highlight_reels":false,
"account_badges":[
],
"latest_reel_media":0
},
{
"pk":7324707263,
"username":"Mike Jones",
"full_name":"Mike",
"is_private":false,
"profile_pic_url":"https://scontent-lga3-1.cdninstagram.com/v/t51.2885-19/293689497_4676376015169654_5558066294974198168_n.jpg?stp=dst-jpg_s150x150&_nc_ht=scontent-lga3-1.cdninstagram.com&_nc_cat=110&_nc_ohc=ErZ3qsP0LsAAX96OT9a&edm=APQMUHMBAAAA&ccb=7-5&oh=00_AT8pFSsMfJz4Wpq5ulTCpou-4jPs3_GBqIT_SQA6YMaQ0Q&oe=62D61C4D&_nc_sid=e5d0a6",
"profile_pic_id":"28817013445468058864_7324707263",
"is_verified":false,
"has_anonymous_profile_picture":false,
"has_highlight_reels":false,
"account_badges":[
],
"latest_reel_media":1657745524
}
]
}
What I'm trying to do is extract the pk variable from all of them.
I know how to do it on a one by one basis as such:
ids = results['users'][1]['pk']
ids = results['users'][2]['pk']
ids = results['users'][3]['pk']
And so on. But let's say I wanted to extract all of those values in one swoop. I also won't necessarily know how many there are in each JSON object (while the example I used had three, it could be hundreds).
I'm so used to R where you can just doing something like ids = results$pk but don't know how to do this with Python.
EDIT BASED ON rv.kvetch answer
data = results
data = json.loads(data)
ids = [u['pk'] for u in data['users']]
print(ids)
But when I run it I get TypeError: the JSON object must be str, bytes or bytearray, not dict
You can load the json string to a dict object, then use a list comprehension to retrieve a list of ids:
import json
# data is a string
data: str = """
...
"""
data: dict = json.loads(data)
ids = [u['pk'] for u in data['users']]
print(ids)
Output:
[54297756964, 182625349, 7324707263]

my loop is only printing the second part of the dictionary , i'm using json

import json
data ='''
{
"names": {"first_boy" : "khaled"},
"names": {"second_boy" : "waseem"}
}
'''
info = json.loads(data)
for line in info:
print(info["names"])
I expected it to print the first_boy and the second_boy dictionary ,but it's printing
{'second_boy': 'waseem'}
Dicts in python can only support one of the same key. Similarly, most implementations of JSON do not allow duplicate keys. The way python handles this, when using json.loads() (or anything else that constructs a dict) is to simply use the most recent definition of any given key.
In this case, {"second_boy":"waseem"} overwrites {"first_boy":"khaled"}.
The problem here is that the key "names" exists 2 times.
Maybe you can do this:
import json
data ='''
{
"names": {"first_boy" : "khaled",
"second_boy" : "waseem"}
}
'''
info = json.loads(data)
for key, value in info['names'].items():
print(key, value)

how to access a dictionary key value in the other key of same dictionary

i am new to python and not getting a way to access the dictionary value in another key of same dictionary.
keys = {
'sample': some_data,
'sample2': keys['sample']
}
The above codeblock gives an TypeError: 'module' object is not subscriptable
Is there anything like this keyword in python to do so.
The keys dictionary doesn't exist when you reference it. You need to define it before referencing it.
This code runs just fine:
some_data = 'xxx'
keys = {
'sample': some_data,
}
keys['sample2'] = keys['sample']
print(keys['sample2'])
Output:
>>> xxx
If you look at your dictionary, you are trying to reference keys inside the keys dictionary itself. Which is impossible since you haven't defined keys in the first place (Circular reference).
The easiest way to avoid it to just do.
keys = {
'sample': some_data,
'sample2': some_data
}

Parsing dynamically changing json file and store it to dict in python

I have dynamically changing json file (not the entire file changes dynamically, its just at one point which I will specify below) and I need to iterate using for loop at that point (where it changed dynamically) so that I can grab required elements inside that bracket in json file. Below is json snippet what it looks like.
"A" : {
"uni/aa/bb" (----> This changes randomly): [ {
"Name" : "cc",
"Id" : "1",
}, {
"Name" : "cc",
"Id" : "1",
} ]
}
I used re.search to match the pattern I get at that point. But no luck. I need to store Name and Id values ultimately. Any suggestions?
resp = json.loads(resp) ---> This gives me above mentioned json output
Here are the sample of codes I am trying.
for k in resp['A']:
for v in k['uni/aa/bb']: #---> TypeError: string indices must be integers
for k in resp['A']:
m = re.search('uni/(.*)') #--> Because this is changing dynamically
if m:
name = str(m['Name']) #---> TypeError: '_sre.SRE_Match' object has no attribute '__getitem__'
If it the case that you always want to know the string key that belongs to the child of "A" object and don't mind removing the item from json, you can try poping the thing. Like this: key, value = resp["A"].popitem(). From this key, you can get those uni/aa/bb strings, whatever it maybe. And after that you can also traverse that child further down the depth like this: resp["A"][key][0]["Name"]. Reference.
Sample code.
Another approach could be like the following. Instead of for v in k['uni/aa/bb']: use this: for key, value in k.items(): in case of python3.x or for key, value in k.iteritems(): for python2.x. Reference.
Sample code.

Accessing elements in dictionary of dictionaries

I am parsing some information from a CSV File and am inputting it into a dict of dicts. The inner dict v contains the following elements {'140725AD4': <mod.City object at 1x3259C2D1>, '631315AD2': <mod.City object at 0x023A4870>}. How would I access the object <mod.city object at 0x0138C3B0> for example?
Thank You.
Having a structure like the following:
john = {
"name": "John",
"family": {
"son": "Ret",
"daughter": "Pat"
}
}
You can access the John son's name like this:
john['family']['son']
This will return "Ret"
In your case, if City object is a DICT you can use:
dict['140725AD4']['population']
If your City object is just a Class you can do
dict['140725AD4'].getPopulation()
or
dict['140725AD4'].population
How it works?
A dictionary is a hashmap of pairs (name, value). Whenever you call a name the value is given. In Python, the value can be anything, from int to a Class.
So when in a dict you ask for a name inside a dict like dict['name'] you get back the value associated with it. In this case its your City object. Then you can call anything related to the value: functions, variables...
Assuming this question is the follow up for this one - Updating Dictionary of Dictionaries in Python you would have to do this:
inner_dict = places["City"]
for _, city_obj in inner_dict.items():
print city_obj.population # Assuming population is one of the member variables of the class mod.city

Categories

Resources