python更新字典下嵌套数组下嵌套字典的值

吃可爱长大的小学妹 提交于 2019-12-06 16:43:46

已知从外层到里层:字典-->数组-->字典的数据:

datas = {'product_info': '[{"qty":"1","name":"football","price":"20","url":"www","attribute":"","image":""}]'}

需要更新qty的值为3

(1)将键product_info的值由str转为dict

import json
product_info_value = json.loads(datas['product_info'])[0]
product_info_value的结果为:
{'qty': '1', 'price': '20', 'url': 'www', 'name': 'football', 'attribute': '', 'image': ''}

(2)更新product_info_value 字典中qty的值

product_info_value['qty'] = '3'

此时product_info_value的结果为:

{'qty': '3', 'price': '20', 'url': 'www', 'name': 'football', 'attribute': '', 'image': ''}

(3)将product_info_value由字典格式变成str,并赋值给datas['product_info'](注意不要漏了[])

datas['product_info'] = json.dumps([product_info_value])

此时键product_info对应的值为:

'[{"qty": "3", "price": "20", "url": "www", "name": "football", "attribute": "", "image": ""}]'

datas的值为: 更新成功

{'product_info': '[{"qty": "3", "price": "20", "url": "www", "name": "football", "attribute": "", "image": ""}]'}

完整代码为:

import json

datas = {'product_info': '[{"qty":"1","name":"football","price":"20","url":"www","attribute":"","image":""}]'}

product_info_value = json.loads(datas['product_info'])[0]
product_info_value['qty'] = '3'
datas['product_info'] = json.dumps([product_info_value])

 

 

 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!