I have a list of dict which I need to parse into a dict {A:[b,c]}.
iam_profile_association = [{'AssociationId': 'iip-assoc-08c2998aabf8ad37e', 'InstanceId': 'i-078cf2f285a2bb4d3', 'IamInstanceProfile': {'Arn': 'arn:aws:iam:::instance-profile/STANDARD-SSM-INSTANCEPROFILE-us-east-1', 'Id': 'AIPAZTOKUMIFDJ4VGT2FP'}, 'State': 'associated'}, {'AssociationId': 'iip-assoc-0afc8368072fa1d7e', 'InstanceId': 'i-076d4c961d800ba18', 'IamInstanceProfile': {'Arn': 'arn:aws:iam:::instance-profile/STANDARD-SSM-INSTANCEPROFILE-us-east-1', 'Id': 'AIPAZTOKUMIFDJ4VGT2FP'}, 'State': 'associated'}, {'AssociationId': 'iip-assoc-0c46d1f23de061e98', 'InstanceId': 'i-0942731f00ebd33e1', 'IamInstanceProfile': {'Arn': 'arn:aws:iam:::instance-profile/STANDARD-SSM-INSTANCEPROFILE-us-east-1', 'Id': 'AIPAZTOKUMIFDJ4VGT2FP'}, 'State': 'associated'}]
iam_dict = {}
for iam_assoc in iam_profile_association:
iam_dict[iam_assoc['InstanceId']] = [iam_assoc['AssociationId'],iam_assoc['IamInstanceProfile']['Arn']]
print (iam_dict)
iam_dict just prints the first value :
{'i-078cf2f285a2bb4d3': ['iip-assoc-08c2998aabf8ad37e', 'arn:aws:iam::660239311370:instance-profile/STANDARD-SSM-INSTANCEPROFILE-us-east-1']}
Can someone help me in this? I would like to store all the values in this dict format.
Your print is inside the for loop, move it outside (tab it in)
iam_dict = {}
for iam_assoc in iam_profile_association:
iam_dict[iam_assoc['InstanceId']] = ...........
print (iam_dict)
It's tricky to work out more than that from what you are asking. But this would be a good start.
Related
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.
I want to perform searches on values in a list of nested dictionaries and return another key:value pairs. These dictionaries are metafiles. Basically I want to search the ID of each dictionary, find all dictionaries that have the same ID, and return the file location (key:value) pairs.
metafile = [{'metadata':{'Title':'The Sun Also Rises', 'ID': 'BAY121-F1164EAB499'}, 'content': 'xyz', 'File_Path': 'file_location1'},
{'metadata':{'Title':'Of Mice and Men', 'ID': '499B0BAB#dfg'}, 'content': 'abc', 'File_Path': 'file_location2'},
{'metadata':{'Title':'The Sun Also Rises Review', 'ID': 'BAY121-F1164EAB499'}, 'content': 'ftw', 'File_Path': 'file_location3'}]
I created a loop to perform my search as follows. It returns an empty list though, how should I modify this so that the file paths are returned?
search_ID = 'BAY121-F1164EAB499'
path =[]
for a in metafile:
for val in a['metadata']['ID']:
if search_ID == val:
path.append(a['File_Path'])
you don't need an inner loop for this:
correct code
search_ID = 'BAY121-F1164EAB499'
path =[]
for a in metafile:
#a['metadata']['ID'] already gives you the value of ID
if search_ID == a['metadata']['ID']:
path.append(a['File_Path'])
output
['file_location1', 'file_location3']
You don't need to iterate through a['metadata']['ID'], instead just access them directly. So the modified code would be
metafile = [{'metadata':{'Title':'The Sun Also Rises', 'ID': 'BAY121-
F1164EAB499'}, 'content': 'xyz', 'File_Path': 'file_location1'},
{'metadata':{'Title':'Of Mice and Men', 'ID': '499B0BAB#dfg'}, 'content': 'abc',
'File_Path': 'file_location2'},
{'metadata':{'Title':'The Sun Also Rises Review', 'ID': 'BAY121-F1164EAB499'},
'content': 'ftw', 'File_Path': 'file_location3'}]
search_ID = 'BAY121-F1164EAB499'
path =[]
for a in metafile:
if a["metadata"]["ID"] == search_ID:
path.append(a['File_Path'])
I'm trying to get two attributes at the time from my json data and add them as an item on my python list. However, when trying to add those two: ['emailTypeDesc']['createdDate'] it throws an error. Could someone help with this? thanks in advance!
json:
{
'readOnly': False,
'senderDetails': {'firstName': 'John', 'lastName': 'Doe', 'emailAddress': 'johndoe#gmail.com', 'emailAddressId': 123456, 'personalId': 123, 'companyName': 'ACME‘},
'clientDetails': {'firstName': 'Jane', 'lastName': 'Doe', 'emailAddress': 'janedoe#gmail.com', 'emailAddressId': 654321, 'personalId': 456, 'companyName': 'Lorem Ipsum‘}},
'notesSection': {},
'emailList': [{'requestId': 12345667, 'emailId': 9876543211, 'emailType': 3, 'emailTypeDesc': 'Email-In', 'emailTitle': 'SampleTitle 1', 'createdDate': '15-May-2020 11:15:52', 'fromMailList': [{'firstName': 'Jane', 'lastName': 'Doe', 'emailAddress': 'janedoe#gmail.com',}]},
{'requestId': 12345667, 'emailId': 14567775, 'emailType': 3, 'emailTypeDesc': 'Email-Out', 'emailTitle': 'SampleTitle 2', 'createdDate': '16-May-2020 16:15:52', 'fromMailList': [{'firstName': 'Jane', 'lastName': 'Doe', 'emailAddress': 'janedoe#gmail.com',}]},
{'requestId': 12345667, 'emailId': 12345, 'emailType': 3, 'emailTypeDesc': 'Email-In', 'emailTitle': 'SampleTitle 3', 'createdDate': '17-May-2020 20:15:52', 'fromMailList': [{'firstName': 'Jane', 'lastName': 'Doe', 'emailAddress': 'janedoe#gmail.com',}]
}
python:
final_list = []
data = json.loads(r.text)
myId = [(data['emailList'][0]['requestId'])]
for each_req in myId:
final_list.append(each_req)
myEmailList = [mails['emailTypeDesc']['createdDate'] for mails in data['emailList']]
for each_requ in myEmailList:
final_list.append(each_requ)
return final_list
This error comes up when I run the above code:
TypeError: string indices must be integers
Desired output for final_list:
[12345667, 'Email-In', '15-May-2020 11:15:52', 'Email-Out', '16-May-2020 16:15:52', 'Email-In', '17-May-2020 20:15:52']
My problem is definetely in this line:
myEmailList = [mails['emailTypeDesc']['createdDate'] for mails in data['emailList']]
because when I run this without the second attribute ['createdDate'] it would work, but I need both attributes on my final_list:
myEmailList = [mails['emailTypeDesc'] for mails in data['emailList']]
I think you're misunderstanding the syntax. mails['emailTypeDesc']['createdDate'] is looking for the key 'createdDate' inside the object mails['emailTypeDesc'], but in fact they are two items at the same level.
Since mails['emailTypeDesc'] is a string, not a dictionary, you get the error you have quoted. It seems that you want to add the two items mails['emailTypeDesc'] and mails['createdDate'] to your list. I'm not sure if you'd rather join these together into a single string or create a sub-list or something else. Here's a sublist option.
myEmailList = [[mails['emailTypeDesc'], mails['createdDate']] for mails in data['emailList']]
Strings in JSON must be in double quotes, not single.
Edit: As well as names.
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'])
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'