zoukankan      html  css  js  c++  java
  • python更新字典下嵌套数组下嵌套字典的值

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

    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])
  • 相关阅读:
    with原理__enter__、__exit__
    os模块walk方法
    restful规范简要概述
    python全栈开发day113-DBUtils(pymysql数据连接池)、Request管理上下文分析
    关于word2016中图片和正文编号自动更新的方法
    秋招
    GIL(全局解释器锁)
    多任务:进程、线程、协程对比
    多任务:协程
    进程和线程的对比
  • 原文地址:https://www.cnblogs.com/kite123/p/11995040.html
Copyright © 2011-2022 走看看