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])
  • 相关阅读:
    <Android 应用 之路> 天气预报(五)
    Java图形界面开发—列出指定目录
    解决The Network Adapter could not establish the connection
    <Android 应用 之路> 天气预报(四)
    Java集合框架—List
    Java集合框架—Map
    C#工程缺少IIS组件无法打开的解决办法
    关于com工程依赖的一些总结
    C:移位运算符
    void类型及void指针
  • 原文地址:https://www.cnblogs.com/kite123/p/11995040.html
Copyright © 2011-2022 走看看