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.
Related
My list like below:
[
{code:"code1",name:"name1",position:"p1"},
{code:"code2",name:"name2",position:"p2"},
......
]
But there is some duplicate code in the list. My question is how to remove the duplicate code from list. I can do it by build for loop and traversal the list again and again, but I think probably there is some straightforward methods can do this in python.
I also need sorted the array by key code, how can I do it without write loop by myself?
Thanks!
You have a list of dictionaries with keys as a variable that are not defined. It throws an error:
NameError: name 'code' is not defined
If I change them to the type string by enclosing the keys in quotes, I get the following:
[
{"code": "code1", "name": "name1", "position": "p1"},
{"code": "code2", "name": "name2", "position": "p2"}.
......
]
Let the above list be some_list. To remove duplicates from the list of dictionaries:
some_list = [dict(t) for t in {tuple(d.items()) for d in some_list}]
To sort the list of dicts by the key code:
some_list = sorted(some_list, key=lambda k: k['code'])
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.
I'm trying to practice sets and dictionaries, and one thing I've been finding is myself stuck on this practice problem over and over.
For example if I have a dictionary like
employees =[
{
"name": "Jamie Mitchell",
"job": "Head Chef",
"city": "Toronto",
},
{
"name": "Michell Anderson",
"job": "Line Cook",
"city": "Mississauga",
}
]
How would I extract the second part of the dictionary from the first in order to only have the information on the right be in a new dictionary?
Quick Answer:
employees is a list of dictionaries so you can just directly index the list to get Michell:
newDict = employees[1]
More Detailed Answer:
Firstly, here is how you create a key-value pair in a dictionary:
dct = {}
dct['color'] = 'blue' # dct = {'color':'blue'}
Knowing this, all you would need to copy a dictionary is the keys and values. You can use the .keys(),.values(), and .items() methods of dictionaries to do this.
dct.keys() # returns a list of all the keys -> ['color']
dct.values() # returns a list of all the values -> ['blue']
dct.items() # return a list of all the pairs as tuples -> [('color','blue')]
There are other options to copy as another user has mentioned however I strongly suggest you get used to work with the 3 methods listed above. If you haven't already, make sure you are really comfortable with lists before you jump into dictionaries and combined structures. You already seem to know how to work loops so hopefully this is helpful enough, good luck!
You have them backwards; the outer one [] is a list. The inner ones {} are dictionaries.
You can get the second one with employees[1] (indexing starts from 0) or the last one with employees[-1] (in this case they are the same).
If you need a copy, you can call .copy() on the result:
second_employee = employees[1]
copied_details = second_employee.copy()
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.
I am attempting to understand how to take a list and convert that into a nested JSON object.
Expected Output
{
"Name1": [
{
"key": "value",
"key": "value",
"key": "value",
"key": "value"
}
],
}
So far my thinking as gone as follows, convert the list to dictionary using comprehension and splitting key value pairs.
list1 = ['key value', 'key value', 'key value']
dict1 = dict(item.split(" ") for item in list1)
I then thought converting that into a JSON object would be something similar to:
print json.loads(dict1)
However, Im not sure how to create the "Name1" parent key. And it seems google is being particularly helpful. Im sure there is something simple im missing, any pointers would be appreacited.
EDIT
Included a list for reference
You simply put them in another dictionary, and use a new list. So:
import json
list1 = ['key1 value1', 'key2 value2', 'key3 value3']
dict1 = {'Name1': [dict(item.split(" ",1) for item in list1)] }
# ^ dict ^ list with 1 element end list ^ ^ end dict
json.dumps(dict1)
And this produces:
>>> print(json.dumps(dict1))
{"Name1": [{"key2": "value2", "key3": "value3", "key1": "value1"}]}
Notes:
A dictionary can only contain different keys (both in JSON and Python);
You better split with .split(" ",1) since if the value contains spaces, these are all seen as still a single value.
dictionaries are unordered, so the order of th keys can be shuffled.