How to get an element value in Python dictionary - python

I am trying to get the value of DomainName from the below dictionary.
print(domain_name)
# output
{
'DomainNames': [
{
'DomainName': 'some-value'
},
]
}
I have tried:
print(domain_name['DomainNames'][0]['DomainName'])
but it doesn't give that value. I even tried:
print(domain_name['DomainNames']['DomainName'])
Here is my code:
def add_es_tags():
for region in get_regions_depending_on_account():
pass
es_client = boto3.client('es', region_name="us-east-1")
response = es_client.list_domain_names()
get_es_domain_ARN("us-east-1", response)
def get_es_domain_ARN(region, domain_names):
es_client = boto3.client('es', region_name=region)
arns = []
print(len(domain_names))
for domain_name in domain_names:
# print(type(domain_name))
print(domain_name['DomainNames'][0]['DomainName'])

Like this:
domain_name = {
'DomainNames': [
{
'DomainName': 'some-value'
},
]
}
print(domain_name)
print(domain_name['DomainNames'][0]['DomainName'])
Yes, the answer is: it works exactly as you suggested!
Edit: Never mind, I'll update this when you've formulated a full question that actually matches what you're doing.

Related

Remove fields from a json array in Python

Currently I have a function returning json via jsonify.
[
{
"hostname": "bla",
"ipaddress": "192.168.1.10",
"subnetmask": "255.255.255.0",
"iloip": "192.168.1.11"
}
]
I want to keep it in json format, but I want to only show the fields I choose (i.e. reduce it). For this example, I want hostname and ipaddress.
Thanks
You can use dict comprehension:
json_input = '''
[
{
"hostname": "bla",
"ipaddress": "192.168.1.10",
"subnetmask": "255.255.255.0",
"iloip": "192.168.1.11"
}
]
'''
desired_keys = {'hostname', 'ipaddress'}
json_filtered = json.dumps([{ k:v for (k,v) in d.items() if k in desired_keys}
for d in json.loads(json_input)])
print(json_filtered)
output:
'[{"hostname": "bla", "ipaddress": "192.168.1.10"}]'
I belive what you want to achieve can be done with the code given below:
import json
data_json = '{"hostname": "bla","ipaddress": "192.168.1.10","subnetmask": "255.255.255.0","iloip": "192.168.1.11"}'
data = json.loads(data_json)
chosen_fields = ['hostname', 'ipaddress']
for field in chosen_fields:
print(f'{field}: {data[field]}')
Output:
hostname: bla
ipaddress: 192.168.1.10
Here what we do is we parse the stringified version of the json using the python's json module (i.e. json.loads(...)). Next decide on the fields we want to access (i.e. chosen_fields). Finally we iterate through the field we want to reach and get the corresponding values of the fields. This leaves the original json unmodified as you wished. Hope this helps.
Or else if you want these fields as a reduced json object:
import json
data_json = '{"hostname": "bla","ipaddress": "192.168.1.10","subnetmask": "255.255.255.0","iloip": "192.168.1.11"}'
data = json.loads(data_json)
chosen_fields = ['hostname', 'ipaddress']
reduced_json = "{"
for field in chosen_fields:
reduced_json += f'"{field}": "{data[field]}", '
reduced_json = list(reduced_json)
reduced_json[-2] = "}"
reduced_json = "".join(reduced_json)
reduced = json.loads(reduced_json)
for field in chosen_fields:
print(f'"{field}": "{reduced[field]}"')
Output:
"hostname": "bla"
"ipaddress": "192.168.1.10"
If I understand you correctly:
import json
response = [
{
"hostname": "bla",
"ipaddress": "192.168.1.10",
"subnetmask": "255.255.255.0",
"iloip": "192.168.1.11",
}
]
desired_keys = ["hostname", "ipaddress"]
new_response = json.dumps(
[{key: x[key] for key in desired_keys} for x in response]
)
And now you have a new_response - valid JSON, with which you can continue to work on

How can I split the path by (".") using python?

-----------------------mapper-------------------
"contact_information":{
"person_name":{
"FormattedName":"some name"
}
}
--------------------current data---------------
client_profile_data = {
"contact_information":{
"person_name":{
"FormattedName":"Abu DND Md"
}
}
}
---------------------changed data------------
profile_data = {
"contact_information":{
"person_name":{
"FormattedName":"Abu DND"
}
}
}
I need to get the changes of "FormattedName(Field)" between client_profile_data & profile_data. So I wrote some function in "helper.py"
------------------------helper.py------------------
PROFILE_FEEDBACK_MAPPINGS = {
'FormattedName': {
'type': 'nested',
'parent_name': "person_name",
'path': "contact_information.person_name.FormattedName"
}
}
def find_diff(client_profile_data, profile_data):
result = []
for key, value in PROFILE_FEEDBACK_MAPPINGS.items():
if value['type'] == 'nested':
try:
if client_profile_data[value['path'][0][1]][key] != profile_data[value['path'][0][1]][key]:
result.append({
'current': profile_data[value['parent_name']][key],
'changed': client_profile_data[value['parent_name']][key],
})
except Exception:
continue
return result
----------------Expected output-------------------
changed: "Abu DND"
current: "Abu DND Md"
-----------------Actual output---------
getting none
Can anyone help me? I need a changes from client_profile_data and profile_data so that I define a function initially which will check the type and after that I want to split the path bcz(contact_information.person_name.FormattedName) will give second if condition will get the differences so that differences will be appending to result. I tried in this way but not working, please help me.
Not sure about what you are looking for but with minimal changes of your code, a solution coud be :
def find_diff(client_profile_data, profile_data):
result = []
for key, value in PROFILE_FEEDBACK_MAPPINGS.items():
if value['type'] == 'nested':
try:
split_path = value['path'].split(".")
client_name = client_profile_data[split_path[0]][split_path[1]][key]
profile_name = profile_data[split_path[0]][split_path[1]][key]
if client_name != profile_name:
result.append({
'current': profile_data[split_path[0]][value['parent_name']][key],
'changed': client_profile_data[split_path[0]][value['parent_name']][key],
})
except Exception:
continue
return result
You forgot to "split" the path to use it as "keys" for your dictionnaries.

Reach one item from an API

I am trying to reach this: 8710002b061e4959ac09c4db1c1b3021 from an API.
I have done this in python:
minecraftName = input("Minecraft Username: ")
f = requests.get(
"https://api.hypixel.net/player?key=[not allowed to show]&name=" + minecraftName).json()
profile = []
profile.append(f["player"]["stats"]["SkyBlock"]["profiles"])
print(profile[:1])
but I get the output:
[{'8710002b061e4959ac09c4db1c1b3021': {'profile_id': '8710002b061e4959ac09c4db1c1b3021', 'cute_name': 'Pear'}}]
and I'm only interested in the first part, or the part by "profile_id". The API looks like this:
"SkyBlock": {
"profiles": {
"8710002b061e4959ac09c4db1c1b3021": {
"profile_id": "8710002b061e4959ac09c4db1c1b3021",
"cute_name": "Pear"
}
}
Try this:
profile = []
profile.append(list(f["player"]["stats"]["SkyBlock"]["profiles"].keys())[0])

Google DLP: "ValueError: Protocol message Value has no "stringValue" field."

I have a method where I build a table for multiple items for Google's DLP inspect API which can take either a ContentItem, or a table of values
Here is how the request is constructed:
def redact_text(text_list):
dlp = google.cloud.dlp.DlpServiceClient()
project = 'my-project'
parent = dlp.project_path(project)
items = build_item_table(text_list)
info_types = [{'name': 'EMAIL_ADDRESS'}, {'name': 'PHONE_NUMBER'}]
inspect_config = {
'min_likelihood': "LIKELIHOOD_UNSPECIFIED",
'include_quote': True,
'info_types': info_types
}
response = dlp.inspect_content(parent, inspect_config, items)
return response
def build_item_table(text_list):
rows = []
for item in text_list:
row = {"values": [{"stringValue": item}]}
rows.append(row)
table = {"table": {"headers": [{"name": "something"}], "rows": rows}}
return table
When I run this I get back the error ValueError: Protocol message Value has no "stringValue" field. Even though the this example and the docs say otherwise.
Is there something off in how I build the request?
Edit: Here's the output from build_item_table
{
'table':
{
'headers':
[
{'name': 'value'}
],
'rows':
[
{
'values':
[
{
'stringValue': 'My name is Jenny and my number is (555) 867-5309, you can also email me at anemail#gmail.com, another email you can reach me at is email#email.com. '
}
]
},
{
'values':
[
{
'stringValue': 'Jimbob Doe (555) 111-1233, that one place down the road some_email#yahoo.com'
}
]
}
]
}
}
Try string_value .... python uses the field names, not the type name.

Behaviour of dictionary.append in python

I am writing some code where my highest aim is, to deliver some information in json format. I want to display servernames and serverurls like this: ( My aim is not the pretty print but I just displayed it like this, so it is more obvious )
{
"server": [
{ "name" : "some_server_name", "url" : "some_server_url" }
{ "name" : "another_server_name", "url" : "another_server_url" }
]
}
I got now two lists, one with the servernames and the other with serverulrs. I iterate over the names and then access to the matching url. After that is done I want to append it to a dictionary. When I got this dictionary. I want to append this to my json_dict. I created that dict because I have two other lists which I want to display too in my json information. ( You can ignore rdp and cert because they are already displayed correctly )
def build_dict(server_name, server_url, rdp, cert):
json_dict = defaultdict(list)
server_dict = {}
if server_name and server_url:
for i, iter_name in enumerate(server_name):
server_dict.update( name = iter_name, url = server_url[i] )
json_dict['server'].append(server_dict)
if rdp:
for iter_rdp in rdp:
json_dict['config'].append(iter_rdp)
if cert:
for iter_cert in cert:
json_dict['cert'].append(iter_cert)
return json_dict
The entries of my servernames list:
[u'123name', u'qwer123']
And the entries of my serverurls list:
[u'123url', u'qwer123']
Unfortunately the final output looks like this:
{"cert": ["123url", "123123", "123123123"],
"config": ["123rdp", "123123", "123123123"],
"server": [
{"url": "qwer123", "name": "qwer123"},
{"url": "qwer123", "name": "qwer123"}
]
}
You can ignore cert and config because this already works as expected. I just don't understand why I have:
{"url": "qwer123", "name": "qwer123"},
{"url": "qwer123", "name": "qwer123"}
And not:
{"url": "123name", "name": "123url"},
{"url": "qwer123", "name": "qwer123"}
as output.
As jonrsharpe stated, you have your server_dict at the wrong place. You should consider putting it in your for loop, so you just update the two entries which you recently received through your for loop.
if server_name and server_url:
for i, iter_name in enumerate(server_name):
server_dict = dict( name = iter_name, url = server_url[i] )
json_dict['server'].append(server_dict)

Categories