Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to loop through dict of list of dict kind of data using python

i am trying to loop through using python

{u'customfield_10067': [u'{"field_type":"cmdb-object-cftype","value":{"workspaceId":"dsjahdjasf-61f7-4421-9ced-df122a122d603","name":"test","objectId":"14","id":"dsjahdjasf-61f7-4421-9ced-df122a122d603:14"}}']}

to get value of custom field in a dict as

{
customfield_10067 : 
{"workspaceId":"dsjahdjasf-61f7-4421-9ced-df122a122d603","objectId":"14","id":"dsjahdjasf-61f7-4421-9ced-df122a122d603:14"}
}

i tried looping as list of dict and dict iteration , however when i loop as a dict it throws error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

TypeError: ValueError('dictionary update sequence element #0 has length 1; 2 is required',) is not JSON serializable

when looping as list of dict
it throws string indices error

any help is much appreciated.

custom_fields = [] regex = '[^A-Za-z0-9]+' project_id = request.data['project_id'] description = re.sub(regex, ' ', str(request.data['description'])) summary = re.sub(regex, ' ', str(request.data['subject'])) issue_type_id = re.sub(regex, '', str(request.data['issuetype'])) request_dict = dict(request.data)

for fields,value in request_dict.items(): if "custom" in fields: custom_data = {fields : value} custom_fields.append(custom_data) # print(custom_fields) for k,v in dict(custom_fields).items(): print(k) print(v)

>Solution :

Maybe eval() will be able to get the work done, though it may need more validations depending on how many strings does your list contain, but you get the idea.

dict_list = {u'customfield_10067': [u'{"field_type":"cmdb-object-cftype","value":{"workspaceId":"dsjahdjasf-61f7-4421-9ced-df122a122d603","name":"test","objectId":"14","id":"dsjahdjasf-61f7-4421-9ced-df122a122d603:14"}}']}
new_dict = {}
for key, value in dict_list.items():
    new_dict[key] = eval(value[0])['value']
print(new_dict)

output:

{'customfield_10067': {'workspaceId': 'dsjahdjasf-61f7-4421-9ced-df122a122d603', 'name': 'test', 'objectId': '14', 'id': 'dsjahdjasf-61f7-4421-9ced-df122a122d603:14'}}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading