How to add key to existing dictionary? - python

I am using python3 and trying to figure out the easiest way to add another layer to my dictionary. I have a dictionary that looks like this.
{ "block1": ["brian"], "block2": ["angel"], "block3": ["sally"] }
How can I add name into the existing dictionary?
{ "name": { "block1": [ "brian" ], "block2": [ "angel" ], "block3": [ "sally" ] } }

d1 = { "block1": ["brian"], "block2": ["angel"], "block3": ["sally"] }
d1 = {"name":d1}
print (d1)

Related

Iterate through a complex dictionary with python

I would like to browse this dictionary especially the lines sub-array
my_dict= {
"alla": "koko",
"messages": [
{
"env": "dlo",
"detail": "cons"
}
],
"commandes": [
{
"comande_numero": "lkm02",
"date": "14/10/2022",
"lignes": [
{
"product": "mango",
"designation": "04 pacquets of mango",
"quantite": 14
},
......
]
}
]
}
I tried
all_product=my_dict['commandes']
for one_ligne in all_product.lignes:
// my code
but i have an error,
So how to browse the rows sub-array located at the dictionary level
"commandes" is a list, not a dictionary, so iterate properly:
all_product=my_dict['commandes']
for product in all_product:
for ligne in product["lignes"]:
// your code
You can chain dictionary keys to access nested items
all_product=my_dict['commandes'][0]
for one_ligne in all_product['lignes']:
product = one_ligne['product']
# my code
or
for one_ligne in my_dict['commandes'][0]['lignes']:
product = one_ligne['product']
# my code

Python 3.8 - Unable to update dictionary

Hello I have this below dictionary that I want to update
{
"Version":"2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Principal":{
"Federated":"arn:aws:iam::111111111111:saml-provider/Test"
},
"Action":"sts:AssumeRoleWithSAML",
"Condition":{
"StringEquals":{
"SAML:aud":"https://signin.aws.amazon.com/saml"
}
}
}
]
}
Want to update it to
{
"Version":"2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Principal":{
"Federated":[
"arn:aws:iam::111111111111:saml-provider/Test",
"arn:aws:iam::111111111111:saml-provider/Test2"
]
},
"Action":"sts:AssumeRoleWithSAML",
"Condition":{
"StringEquals":{
"SAML:aud":"https://signin.aws.amazon.com/saml"
}
}
}
]
}
i.e. add "arn:aws:iam::111111111111:saml-provider/Test2" to "Federated" and also make it a list. Below is my code
new_arn = "arn:aws:iam::111111111111:saml-provider/Test2"
my_dict = {
"Version":"2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Principal":{
"Federated":[
"arn:aws:iam::111111111111:saml-provider/Test",
]
},
"Action":"sts:AssumeRoleWithSAML",
"Condition":{
"StringEquals":{
"SAML:aud":"https://signin.aws.amazon.com/saml"
}
}
}
]
}
for b in my_dict['Statement']:
updated_arn = f"['{b['Principal']['Federated']}', {new_arn}]"
b['Principal']['Federated']: updated_arn
print(my_dict)
I am bit new to python and I am not sure what am I doing wrong the dict is not getting updated. Can someone please provide some guidance on what I may be doing wrong
As folks commented, you're constructing a string that looks like a list here:
for b in my_dict['Statement']:
updated_arn = f"['{b['Principal']['Federated']}', {new_arn}]"
b['Principal']['Federated']: updated_arn
You can create a real list instead:
for b in my_dict['Statement']:
updated_arn = [b['Principal']['Federated'], new_arn]
b['Principal']['Federated'] = updated_arn
# note it's `=` not `:` here
Edit:
If Federated is sometimes a string, and sometimes already a list, you'll need to check its type and act accordingly:
for b in my_dict['Statement']:
federated = b['Principal']['Federated']
if isinstance(federated, list):
federated.append(new_arn)
# (which updates the list within the dict, no need to assign back to the dict)
else:
b['Principal']['Federated'] = [federated, new_arn]
You can append to the current value of "Federated" as follows:
for b in my_dict['Statement']:
b['Principal']['Federated'].append(new_arn)

Is there a way to get the particular Values from JSON Array using robot or Python code?

JSON OUTPUT:
${response}= [
{
"Name":"7122Project",
"checkBy":[
{
"keyId":"NA",
"target":"1232"
}
],
"Enabled":false,
"aceess":"123"
},
{
"Name":"7122Project",
"checkBy":[
{
"keyId":"_GU6S3",
"target":"123"
}
],
"aceess":"11222",
"Enabled":false
},
{
"Name":"7122Project",
"checkBy":[
{
"keyId":"-1lLUy",
"target":"e123"
}
],
"aceess":"123"
}
]
Need to get the keyId values from json without using hardcoded index using robot?
I did
${ID}= set variable ${response[0]['checkBy'][0]['keyId']}
But I need to check the length get all keyID values and store the values that dose not contain NA
How can I do check length and use for loop using robot framework?
I suppose you can have more elements in checkBy arrays, like so:
response = [
{
"Name":"7122Project",
"checkBy": [
{
"keyId": "NA",
"target": "1232"
}
],
"Enabled": False,
"aceess": "123"
},
{
"Name": "7122Project",
"checkBy": [
{
"keyId": "_GUO6g6S3",
"target": "123"
}
],
"aceess": "11222",
"Enabled": False
},
{
"Name": "7122Project",
"checkBy": [
{
"keyId": "-1lLlZOUy",
"target": "e123"
},
{
"keyId": "test",
"target": "e123"
}
],
"aceess": "123"
}
]
then you can key all keyIds in Python with this code:
def get_key_ids(response):
checkbys = [x["checkBy"] for x in response]
key_ids = []
for check_by in checkbys:
for key_id in check_by:
key_ids.append(key_id["keyId"])
return key_ids
for the example above, it will return: ['NA', '_GUO6g6S3', '-1lLlZOUy', 'test_NA'].
You want to get both ids with NA and without NA, so perhaps you can change the function a bit:
def get_key_ids(response, predicate):
checkbys = [x["checkBy"] for x in response]
key_ids = []
for check_by in checkbys:
for key_id in check_by:
if predicate(key_id["keyId"]):
key_ids.append(key_id["keyId"])
return key_ids
and use it like so:
get_key_ids(response, lambda id: id == "NA") # ['NA']
get_key_ids(response, lambda id: id != "NA") # ['_GUO6g6S3', '-1lLlZOUy', 'test_NA']
get_key_ids(response, lambda id: "NA" in id) # ['NA', 'test_NA']
get_key_ids(response, lambda id: "NA" not in id) # ['_GUO6g6S3', '-1lLlZOUy']
Now it's just a matter of creating a library and importing it into RF. You can get inspiration in the official documentation.
But I need to check the length get all keyID values and store the values that dose not contain NA
I don't completely understand what you are up to. Do you mean length of keyId strings, like "NA" and its length of 2, or the number of keyIds in the response?
How can I do check length and use for loop using robot framework?
You can use keyword Should Be Equal * from BuiltIn library. Some examples of for loops could be found in the user guide here.
Now you should have all the parts you need to accomplish your task, you can try to put it all together.

How to get this json object in python?

so I want to get the first key element from this JSON using python 3.7 without knowing its name.
Here is the JSON:
{
"intent":[
{
"confidence":0.99313362101529,
"value":"sendmessage"
}
],
"wikipedia_search_query":[
{
"suggested":true,
"confidence":0.93804001808167,
"value":"message",
"type":"value"
}
],
"messenger_recipient":[
{
"confidence":0.93138399364195,
"value":"me",
"type":"value"
}
]
}
EDIT:
I want to compare the name of the first key like so:
if(jsonobj[0] == "wikipedia_search_query")
dosomething()
While Python 3.6+ does maintain insertion order on dictionaries, there's no guarantee that your incoming JSON will be in the order you expect. That being said, if you can guarantee the insertion order, here's a working example.
import json
js = """{
"intent":[
{
"confidence":0.99313362101529,
"value":"sendmessage"
}
],
"wikipedia_search_query":[
{
"suggested":true,
"confidence":0.93804001808167,
"value":"message",
"type":"value"
}
],
"messenger_recipient":[
{
"confidence":0.93138399364195,
"value":"me",
"type":"value"
}
]
}"""
json_data = json.loads(js)
first_key = next(iter(json_data))
first_value = json_data[next(iter(json_data))]
print(first_key)
print(first_value)
Output
intent
[{'confidence': 0.99313362101529, 'value': 'sendmessage'}]

How to trim JSON array to get specific value

So I am using the Echo Arena API Which gives me some of the following in JSON Format. I am trying to get all of the NAMES of users in the match at the time, as seen here there is player name: rnedds and further down DarkCobra866. How can I get just the names and none of the other information? Using Python 3.
{
"teams":[
{
"players":[
{
"name":"rnedds",
"rhand":[
-3.3230002,
-1.2370001,
-18.701
],
"playerid":0,
"position":[
-2.7520001,
-0.96800005,
-18.622002
],
"lhand":[
-2.414,
-1.5630001,
-18.487001
],
"userid":1663152230440088,
"stats":{ }
},
{
"name":"DarkCobra866",
"rhand":[
-5.3710003,
-1.978,
-7.5110002
],
"playerid":4,
"position":[
-5.5280004,
-1.3520001,
-7.4040003
],
"lhand":[
-5.6520004,
-1.7540001,
-7.4020004
],
"userid":2649496045086049,
"stats":{ }
}
]
}
]
}
Currently, my code looks like this for other information in the API
matchdetails = {
'echosessionid' : data['sessionid'],
'echoclientname' : data['client_name'],
'echogameclockdisplay' : data['game_clock_display'],
'echogamestatus' : data['game_status']
}
currentMatchDetails = json.dumps(matchdetails)
Load your JSON string into a dictionary like this:
import json
json_text = '''
{
"teams":[
{
"players":[
{
"name":"rnedds",
"rhand":[
-3.3230002,
-1.2370001,
-18.701
],
"playerid":0,
"position":[
-2.7520001,
-0.96800005,
-18.622002
],
"lhand":[
-2.414,
-1.5630001,
-18.487001
],
"userid":1663152230440088,
"stats":{ }
},
{
"name":"DarkCobra866",
"rhand":[
-5.3710003,
-1.978,
-7.5110002
],
"playerid":4,
"position":[
-5.5280004,
-1.3520001,
-7.4040003
],
"lhand":[
-5.6520004,
-1.7540001,
-7.4020004
],
"userid":2649496045086049,
"stats":{ }
}
]
}
]
}
'''
data = json.loads(json_text)
players = [player['name'] for team in data['teams'] for player in team['players']]
print(players)
The above code will result in:
['rnedds', 'DarkCobra866']

Categories

Resources