Accessing Data Nested in Dictionary in Array in Dictionary - python

I'm feeling stumped and looking for help. I'm trying to access data that lives inside of a dictionary that's inside of an array that is inside of a dictionary. See below:
{
'files': [
{
'type': 'diskDescriptor',
'name': '[VM] VM1/VM1.vmdk',
'key': 4,
'size': 0
},
{
'type': 'diskExtent',
'name': '[VM] VM1/VM1-flat.vmdk',
'key': 5,
'size': 32457621504
}
],
'capacity': 32505856,
'label': 'Hard disk 1',
'descriptor': '[VM] VM1/VM1.vmdk',
'committed': 31696896,
'device': {
'summary': '32,505,856 KB',
'_obj': <pysphere.vi_property.VIProperty object at 0x17442910>,
'unitNumber': 0,
'key': 2000,
'label': 'Hard disk 1',
'type': 'VirtualDisk',
'capacityInKB': 32505856
}
}
If I want to access, let's say the descriptor key value how would I go about this with Python? For some reason all of the combinations I've tried do not work.
Any help and guidance would be appreciated and if more information is needed I can provide. Thanks.

Lets call your main dictionary bob, because I like bob:
bob['files'] #get you the list with second dictionary
bob['files'][0] #get you the first item in the list, which is the nested 2nd dictionary
bob['files'][0]['type'] == 'diskDescriptor'

Related

Add an object to every json array in python

I'm trying to figure out how to add the same object to every array.
I'm requesting data from the server for the "first game". When I get it back, it doesn't include any data referencing the first game. So I need to edit it before I send it to my server to save.
I have a json request that looks like this:
{
'dateTime': '2022-07-01T01:00:00.000000',
'httpStatus': 'OK',
'message': 'SUCCESS',
'details': None,
'detailsList': [
{
'date': '2021-07-01T00:00:00',
'tcount': 0,
'first_name': 'Sam',
'last_name': 'Smith'
},
{
'user_reg_date': '2022-06-01T00:00:00',
'tcount': 0,
'first_name': 'Bob',
'last_name': 'Jones'
}]
}
I'm trying to figure out how to add an object to each json array (hope I'm saying that the right way) before I then send it to a mongodb.
In this example:
'game': 'first'
It would then look like this:
{
'dateTime': '2022-07-01T01:00:00.000000',
'httpStatus': 'OK',
'message': 'SUCCESS',
'details': None,
'detailsList': [
{
'date': '2021-07-01T00:00:00',
'tcount': 0,
'first_name': 'Sam',
'last_name': 'Smith',
'game': 'first'
},
{
'user_reg_date': '2022-06-01T00:00:00',
'tcount': 0,
'first_name': 'Bob',
'last_name': 'Jones',
'game': 'first'
}]
}
if there is a better way to do this, that would work as well.
Your asking something similar to this question. But want to loop through a JSON array in Python.
You are not trying to add an 'object' to json 'array'. You have a JSON object, of which there are object members (or more commonly, properties). You have an array as an object member of which you want to modify each object in the array to add a new property.
The code below is the above link with some modification to fit your needs. request_data is the JSON object you give in your example above. You need enumerate to know which index to edit.
for index, item in enumerate(request_data['detailsList']):
# Edit the array entry
item["game"] = 'first'
# Save it
request_data['detailsList'][index] = item

Python match nested structure

Im trying to define some logic, that verifies everything in one nested dictionary belongs to another nested nested dictionary.
Ie:
official_data = {
'Name': 'John Smith',
'ID': 123123232,
'Family': [
{'Name': 'Sarah Smith','ID': 12312323},
{'Name': 'Joe Smith','ID': 12312324}
{'Name': 'Tim Smith','ID': 12312325}
{'Name': 'Sally Smith','ID': 12312326}
],
'Info': {
'InfoList': [
{'text': ['Personal Info Message']},
{'text': ['Secondary Message']}
]
}
}
sample_data = {
'Family': [
{"Name": 'Joe Smith'}
],
'Info': {
'InfoList': [
{'text': ['Secondary Message']}
]
}
}
matches(official_data, sample_data) # True, because everything in sample data exists in official_data, despite official_data having MORE values.
different_sample = {
'Info': {
'InfoList': [{}]
}
}
matches(official_data, different_sample) # True, because the structure of Dict -> Dict -> List -> Dict exists
bad_data = {'ID': 54242343}
matches(official_data, bad_data) # False, because the ID of bad_data is not the ID of official_data
other_bad_data = {
'Info': {
'InfoList': {}
}
}
matches(official_data, other_bad_data) # False, because InfoList is a list in official data
I have a feeling such logic SHOULD be easy to implement, or has already been implemented and is in wide use, but I am struggling to find what i want, and implementing it on my own becomes complicated, with recursive solutions and casting lists into sets in order to make sure order is ignored.
Im wondering if im missing something obvious, or if this logic is actually really niche and would have to be designed from scratch.

Add key and dictionary as key-value pair into existing dictionary

I'd like to add
"5f6c" as a key with values as photo_dict = {'caption': 'eb test', 'photo_id':'330da114-e41e-4cee-ba15-f9632'} into the below using python. I am not sure how to go about it
{'record': {'status': 'bad', 'form_id': '16bba1', 'project_id': None, 'form_values': {'5121':
'yes', '8339': 'ZTVPNG', '6cd3': '234624', '6b5b': '105626', 'e1f6': '[]', '5f6c': [{'id':
'f6efe67d7c5', 'created_at': '1614189636', 'updated_at': '1614189636', 'form_values': {'4ba6':
'Gaaaaah!'}}}
Such that the dictionary becomes
{'record': {'status': 'bad', 'form_id': '16bba1', 'project_id': None, 'form_values': {'5121':
'yes', '8339': 'ZTVPNG', '6cd3': '234624', '6b5b': '105626', 'e1f6': '[]', '5f6c': [{'id':
'f6efe67d7c5', 'created_at': '1614189636', 'updated_at': '1614189636', 'form_values': {'4ba6':
'Gaaaaah!', '5f6c': [{'caption': eb test, 'photo_id': '330da114-e41e-4cee-ba15-f9632'}]}}}
So it seems your initial dictionary is incorrectly formed and does not fully match what you are asking in the question, I would start by updating it with a correct format .
That being said, I ll assume the format would be close to this:
{
"record":{
"status":"bad",
"form_id":"16bba1",
"project_id":"None",
"form_values":{
"5121":"yes",
"8339":"ZTVPNG",
"6cd3":"234624",
"6b5b":"105626",
"e1f6":"[]",
"5f6c":[
{
"id":"f6efe67d7c5",
"created_at":"1614189636",
"updated_at":"1614189636",
"form_values":{
"4ba6":"Gaaaaah!",
"5f6c": {
"caption":"eb test",
"photo_id":"330da114-e41e-4cee-ba15-f9632"
}
}
}
]
}
}
}
You want to modify 5f6c with value
{'caption': 'eb test', 'photo_id':'330da114-e41e-4cee-ba15-f9632'}
Its not very clear which key you actually want to modify as the key 5f6c can be found in two different place in your dict, but it seems what you are trying to do is just modify a dictionary.
So what you need to take away from this is that to modify a dictionary and list you simply do
myDict[key] = value
myList[indice] = value
You contact as much as you want the operation in the same line.
If we take your example from above, and try to modify the most narrowed value, it would give us
import json
records = json.loads(theString)
records['record']['form_values']['5f6c'][0]['form_values']['5f6c'] = {"caption":"eb test", "photo_id":"330da114-e41e-4cee-ba15-f9632" }
After correcting your formatting I would do this.
my_dict = {'record': {'status': 'bad',
'form_id': '16bba1',
'project_id': None,
'form_values': {'5121': 'yes',
'8339': 'ZTVPNG',
'6cd3': '234624',
'6b5b': '105626',
'e1f6': '[]',
'5f6c': [{'id': 'f6efe67d7c5',
'created_at': '1614189636',
'updated_at': '1614189636',
'form_values': {'4ba6': 'Gaaaaah!'}
}
]}
}
}
photo_dict = {'caption': 'eb test', 'photo_id':'330da114-e41e-4cee-ba15-f9632'}
my_dict['record']['form_values']['5f6c'][0]['form_values']['5f6c'] = photo_dict
By the way you can get tools in your IDE that will help you with formatting and handle it for you.

Filter python dictionary with dictionary-comprehension

I have a dictionary that is really a geojson:
points = {
'crs': {'properties': {'name': 'urn:ogc:def:crs:OGC:1.3:CRS84'}, 'type': 'name'},
'features': [
{'geometry': {
'coordinates':[[[-3.693162104185235, 40.40734504903418],
[-3.69320229317164, 40.40719570724241],
[-3.693227952841606, 40.40698546120488],
[-3.693677594635894, 40.40712700492216]]],
'type': 'Polygon'},
'properties': {
'name': 'place1',
'temp': 28},
'type': 'Feature'
},
{'geometry': {
'coordinates': [[[-3.703886381691941, 40.405197271972035],
[-3.702972834622821, 40.40506272989243],
[-3.702552994966045, 40.40506798079752],
[-3.700985024825222, 40.405500820623814]]],
'type': 'Polygon'},
'properties': {
'name': 'place2',
'temp': 27},
'type': 'Feature'
},
{'geometry': {
'coordinates': [[[-3.703886381691941, 40.405197271972035],
[-3.702972834622821, 40.40506272989243],
[-3.702552994966045, 40.40506798079752],
[-3.700985024825222, 40.405500820623814]]],
'type': 'Polygon'},
'properties': {
'name': 'place',
'temp': 25},
'type': 'Feature'
}
],
'type': u'FeatureCollection'
}
I would like to filter it to stay only with places that have a specific temperature, for example, more than 25 degrees Celsius.
I have managed to do it this way:
dict(crs = points["crs"],
features = [i for i in points["features"] if i["properties"]["temp"] > 25],
type = points["type"])
But I wondered if there was any way to do it more directly, with dictionary comprehension.
Thank you very much.
I'm very late. A dict compreheneison won't help you since you have only three keys. But if you meet the following conditions: 1. you don't need a copy of features (e.g. your dict is read only); 2. you don't need index access to features, you my use a generator comprehension instead of a list comprehension:
dict(crs = points["crs"],
features = (i for i in points["features"] if i["properties"]["temp"] > 25),
type = points["type"])
The generator is created in constant time, while the list comprehension is created in O(n). Furthermore, if you create a lot of those dicts, you have only one copy of the features in memory.

Trouble accessing a value from a dictionary

I have the following dictionary
Dict = {'Manu':{u'ID0020879.07': [{'ID': u'ID0020879.07', 'log': u'log-123-56', 'owner': [Manu], 'item': u'WRAITH', 'main_id': 5013L, 'status': u'noticed', 'serial': u'89980'}]}}
How can I access the serial from this dictionary?
I tried Dict['Manu']['serial'], But its not working as expected..
Guys any idea?
Your dictionary is very nested one.Try like this.
In [1]: Dict['Manu']['ID0020879.07'][0]['serial']
Out[1]: u'89980'
Here is the restructured dictionary.
{
'Manu': {
u'ID0020879.07': [{
'ID': u'ID0020879.07',
'log': u'log-123-56',
'owner': [Manu],
'item': u'WRAITH',
'main_id': 5013L,
'status': u'noticed',
'serial': u'89980'
}]
}
}
Now, you can see where the serial key is located more clearly (not under Manu)...
It is instead
Dict['Manu']['ID0020879.07'][0]['serial']
I suggest you fix that data source to not make ID0020879.07 a key of the data (because it is duplicated in the ID key of that object in the list).
Perhaps fix like so where the Manu key maps to a list of "accounts", each with an ID and other fields
{
'Manu': [{
'ID': u'ID0020879.07',
'log': u'log-123-56',
'owner': [Manu],
'item': u 'WRAITH',
'main_id': 5013L,
'status': u'noticed',
'serial': u'89980'
}]
}
And then you could do
Dict['Manu'][0]['serial']
Or loop the list to get all the serial keys
for item in Dict['Manu']:
print(item['serial'])

Categories