Find a specific key in python dictionary inside a list - python

I have a list of dictionaries and I am looking to get a specific key at a certain index
[
{
"id":"23fr3yf48",
"type":"engine",
"details":{
"text":"New",
"type":"SPT_2048",
"id":"7033_Q-156",
"engine_details":{
"dateCreated":"2021-08-13 08:59:32.870953+00:00",
"createdBy":"John",
},
},
"confirm":true
},
{
"id":"3u823983hf",
"type":"wheel",
"details":{
"text":"Old",
"type":"SPT_0006",
"id":"101841_2004497"
},
"confirm":true
},
]
In this JSON I want to get the 'id' inside 'details' dict. I specifically want to get the 'details' from the index 1 that has id - '101841_2004497' skipping the 0th index. I want to know to iterate through the list and find the specific index. Can someone help me with this?

This is a simple for loop to check each item in list if the id of its details is equal to the value which you mentioned: 101841_2004497
for item in list:
if item["details"]["id"] == "101841_2004497":
print(item["details"])
JSON response:
{'text': 'Old', 'type': 'SPT_0006', 'id': '101841_2004497'}
Hope it helps!

You don't need to iterate through the list - you can directly access an item by its index. See, for example the Python tutorial.

Related

How to change the value of a JSON list?

I know for fact that this question has been asked before. I looked at the following posts:
Python replace values in unknown structure JSON file
How to find and replace a part of a value in json file
https://pretagteam.com/question/how-to-replace-a-value-in-json-file-using-python
How to find and replace a part of a value in json file (Somehow this is what I am looking for but it does not fit my problem with the links being different and stored all under "latest")
and much more contributions, however I am still stuck.
I have a simple JSON structure like this:
{
"guild1": {
"latest": [
"link1",
"link2"
],
"channel": channel_here
},
"guild2": {
"latest": [
"link"
],
"channel": channel_here
}
}
I found a way to iterate over the entries and print the list in which the condition is found, for example:
# searching for link 1
["link1", "link2", "link3"] # here link 1 for example is found in one of the list entries
["link5"] -> This for example does not match what I am looking for, I can ignore this
If found, I simply want to replace it (just link1) with another before defined value. I tried to iterate over the keys of the found list but was not able to .replace it or something else. The key which matches my search criteria is printed out, but I can't do anything else with it. Is it even possible to change the entry in a list that easy?
Mostly I also got the following error which I also looked up but did not get any did not get any wiser:
TypeError: string indices must be integers
Here is how I search for the list end the "entries":
if defined_link in data[searchloop]['latest']: # data is my JSON file, searchloop the for-loop
for key in data[searchloop]['latest']: # Get all the matching keys
if key == defined_link: # Get the key I am looking for
Maybe someone else can help me here!
This code would change one value in a list (here 'link1') to another:
L = ["link1", "link2", "link3"]
L[L.index('link1')] = 'someOtherValue'
After this you would see that L changed to ["someOtherValue", "link2", "link3"]
You first find at which index is 'link1', let's say you get back 3. So, you know you have to change the value of L[3]. Now it's simple. Do L[3] = 'someOtherValue'.
Iterate over each guild in the json structure.
Iterate over each link in that guild's "latest" list.
If the link matches, assign that list item to something else.
for guild in jsonstructure:
for i in range(len(jsonstructure[guild]['latest'])):
if jsonstructure[guild]['latest'][i] == 'something':
jsonstructure[guild]['latest'][i] = 'new thing'
I think you should try
list.append(i)
It will work I faced same problem
For example:
string = "Hello World!"
list = []
for i in string:
list.append(string[i])
print(list)

How can I analyse an response.text in Python?

Hope you can help me with this question:
master_dict = {"Item": {"last_data": {"S": {"id":2689,
"type":"question",
"number":12,
"offset":12,
"status":0,
"options": [ {"id":8045, "option":"opcion1"},
{"id":8046, "option":"opcion2"},
{"id":8044, "option":"opcion3"}],
"question":"question question question?",
"ts":1576192609
}
}
}
}
This is a dictionary of dictionaries.
How can I do so that I only print the "question" chain?
As you have a dictionary of dictionaries, accessing each dictionary value will give you another dictionary. You can then access the values from that dictionary in the same way. For your particular example, you can do the following:
>>> master_dict["Item"]["last_data"]["S"]["question"]
'question question question?'
If instead, you want to access all occurrences of a certain key in a nested dictionary, this question should help you.

How to extract nested JSON data?

I am trying to get a value from a data JSON. I have successfully traversed deep into the JSON data and almost have what I need!
Running this command in Python :
autoscaling_name = response['Reservations'][0]['Instances'][0]['Tags']
Gives me this :
'Tags': [{'Key': 'Name', 'Value': 'Trove-Dev-Inst : App WebServer'}, {'Key': 'aws:autoscaling:groupName', 'Value': 'CodeDeploy_Ernie-dev-Autoscaling-Deploy_d-4WTRTRTRT'}, {'Key': 'CodeDeployProvisioningDeploymentId', 'Value': 'd-4WTRTRTRT'}, {'Key': 'Environment', 'Value': 'ernie-dev'}]
I only want to get the value "CodeDeploy_Ernie-dev-Autoscaling-Deploy_d-4WTRTRTRT". This is from the key "aws:autoscaling:groupName".
How can I further my command to only return the value "CodeDeploy_Ernie-dev-Autoscaling-Deploy_d-4WTRTRTRT"?
Is this the full output? This a dictionary containing a list with nested dictionaries, so you should treat it that way. Suppose it is called:
A = {
"Tags": [
{
"Key": "Name",
"Value": "Trove-Dev-Inst : App WebServer"
},
{
"Key": "aws:autoscaling:groupName",
"Value": "CodeDeploy_Ernie-dev-Autoscaling-Deploy_d-4WTRTRTRT"
},
{
"Key": "CodeDeployProvisioningDeploymentId",
"Value": "d-4WTRTRTRT"
},
{
"Key": "Environment",
"Value": "ernie-dev"
}
]
}
Your first adress the object, then its key in the dictionary, the index within the list and the key for that dictionary:
print(A['Tags'][1]['Value'])
Output:
CodeDeploy_Ernie-dev-Autoscaling-Deploy_d-4WTRTRTRT
EDIT: Based on what you are getting then you should try:
autoscaling_name = response['Reservations'][0]['Instances'][0]['Tags'][1]['Value']
You could also use glom it's great for deeply nested functions and has sooo many uses that make complicated nested tasks easy.
For example translating #Celius's answer:
glom(A, 'Tags.1.Value')
Returns the same thing:
CodeDeploy_Ernie-dev-Autoscaling-Deploy_d-4WTRTRTRT
So to answer your original question you'd use:
glom(response, 'Reservations.0.Instances.0.Tags.1.Value')
The final code for this is -
tags = response['Reservations'][0]['Instances'][0]['Tags']
autoscaling_name = next(t["Value"] for t in tags if t["Key"] == "aws:autoscaling:groupName")
This also ensures that if the order of the data is moved in the JSON data it will still find the correct one.
For anyone struggling to get their heads around list comprehensions and iterators, the cherrypicker package (pip install --user cherrypicker) does this sort of thing for you pretty easily:
from cherrypicker import CherryPicker
tags = CherryPicker(response['Reservations'][0]['Instances'][0]['Tags'])
tags(Key="aws:autoscaling:groupName")[0]["Value"].get()
which gives you 'CodeDeploy_Ernie-dev-Autoscaling-Deploy_d-4WTRTRTRT'. If you're expecting multiple values, omit the [0] to get back a list of all values that have an associated "aws:autoscaling:groupName" key.
This is probably all a bit overkill for your question, which can be solved easily with a simple list comprehension. But this approach might come in handy if you need to do more complicated things later, like matching on partial keys only (e.g. aws:* or something more complicated like a regular expression), or you need to filter based on the values in an intermediate layer of the nested object. This sort of task could lead to lots of complicated nested for loops or list comprehensions, whereas with CherryPicker it stays as a simple, potentially one-line command.
You can find out more about advanced usage at https://cherrypicker.readthedocs.io.

TypeError : Trouble accessing JSON metadata with Python

So I'm trying to access the following JSON data with python and when i give the statement :
print school['students']
The underlying data gets printed but what I really want to be able to do is print the 'id' value.
{ 'students':[
{
'termone':{
'english':'fifty',
'science':'hundred'
},
'id':'RA1081310005'
}
]
}
So when I do the following I get an error :
print school ['students']['id']
TypeError: list indices must be integers, not str
Can anyone suggest how i can access the ID & where I'm going wrong!
school['students'] is a list. You are trying to access the first element of that list and id key belongs to that element. Instead, try this:
school['students'][0]['id']
Out: 'RA1081310005'
The problem here is that in your list, 'id' is not a part of a dictionary, it is part of a list. To fix this, change your dictionary to the following:
school = {'students':{
'termone': {
"english": "fifty:,
"science": "hundred
},
"id":"RA1081310005"
}
}
Basically, you have a list, and there is no reason to have it, so I removed it.

Appending something to a list within a dict within a list in Python

I am attempting to create a list of dicts which will have the following structure:
[
{
'id': '234nj233nkj2k4n52',
'embedded_list': []
},
{
'id': 'jb234bhj23423h4b4',
'embedded_list': []
},
...
]
Initially, this list will be empty.
What I need to be able to do is:
Check to see if a dict with a specific id exists in the list already
If a dict containing that id exists, append something to it's embedded_list
If a dict containing that id does not exist, create a dict, append it to the list.
I am aware of being able to test if a dict exists in a list based on something inside that dict using something like this:
extracted_dict = next((item for item in list if item['id'] == unique_id), None)
I am unsure of how to append something to a list within a dict within a list efficiently. Is there an obvious way which I'm not seeing (probably)?
Thank you in advance.
Your data structure should be a dictionary of dictionaries in the first place:
{'234nj233nkj2k4n52': {'embedded_list': []},
'jb234bhj23423h4b4': {'embedded_list': []},
... }
This will make all your desired operations much easier. If the inner dictionaries only contain the embedded list, this can be further simplified to
{'234nj233nkj2k4n52': [],
'jb234bhj23423h4b4': [],
... }
Now, all you need is a collections.defaultdict(list):
from collections import defaultdict
d = defaultdict(list)
d['234nj233nkj2k4n52'].append(whatever)
or just a simple dic
{
'234nj233nkj2k4n52' : [],
'jb234bhj23423h4b4' : []
}

Categories