已知二维字典:
datas = {'pay_method_info': '{"card_no":"123456789","expiration_month":"06","expiration_year":"28","cvv":"123","first_name":"sdss","last_name":"kite"}'}
(1)需要更新card_no的值为:123456
card_no_refresh = {"card_no": "123456"}
(2)取出pay_method_info的值,并且由str转为dict,方便对card_no键值对进行操作
import json pay_method_info_value = json.loads(datas['pay_method_info'])
此时的结果pay_method_info_value 为:
{"card_no":"123456789","expiration_month":"06","expiration_year":"28","cvv":"123","first_name":"sdss","last_name":"kite"}
(3)更新card_no的值
pay_method_info_value.update(card_no_refresh)
此时的结果pay_method_info_value 为:
{'first_name': 'sdss', 'expiration_month': '06', 'card_no': '123456', 'expiration_year': '28', 'cvv': '123', 'last_name': 'kite'}
此时的结果datas为:可见并未更新
{'pay_method_info': '{"card_no":"123456789","expiration_month":"06","expiration_year":"28","cvv":"123","first_name":"sdss","last_name":"kite"}'}
(4)使原来的二维字典datas也更新了:需要将我们取出来的pay_method_info_value的格式由当前的dict转为str
datas['pay_method_info'] = json.dumps(pay_method_info_value)
此时查看datas的结果:更新成功啦
{'pay_method_info': '{"first_name": "sdss", "expiration_month": "06", "card_no": "123456", "expiration_year": "28", "cvv": "123", "last_name": "kite"}'}
完整代码如下:
import json datas = {'pay_method_info': '{"card_no":"123456789","expiration_month":"06","expiration_year":"28","cvv":"123","first_name":"sdss","last_name":"kite"}'} card_no_refresh = {"card_no": "123456"} pay_method_info_value = json.loads(datas['pay_method_info'])# 将str转化成dict,更新字典中的值 pay_method_info_value.update(card_no_refresh) datas['pay_method_info'] = json.dumps(pay_method_info_value)# 将dict转化成str,作为字典的值传回去