概述
一、用法
python字典中的update方法可用于字典的键值对更新、添加。示例:
dic = {"zhangsan": 89}
dic.update({"lisi":88})
dic
{'zhangsan': 89, 'lisi': 88}
二、bug描述
在构造数据的时候,如下更新字典bank_code,定义在for循环以外时,会导致所有的banl_code都是PSBC:
test_data = {
"top": "2",
"busId": "XXXX",
"features":
{
"applist": "(38)嘻哈龟牛皮兔,10-10 极端令人惊异的网格块益智世界游戏"
},
"multiFeatures": {}
}
s = 'ICBC CNCB PSBC'
dic = {"tag20": 0, "tag21": 0, "tag22": 1, "tag23": 1, "tag24": 0, "tag25": 1, "tag26": 0, "tag27": 0, "tag17": 0,
"bank_code": "BCOM", "tag30": 0, "tag8": 0, "tag31": 1, "tag10": 0, "tag32": 0, "tag9": 0,
}
for i in s.split(' '):
dic['bank_code'] = i
new_d = {}
new_d[str(i)] = dic
test_data['multiFeatures'].update(new_d)
print(test_data)
三、解决方法
将dic 定义在for循环以内,完美解决,不会导致所有的bank_code都是PSBC:
test_data = {
"top": "2",
"busId": "XXXX",
"features":
{
"applist": "(38)嘻哈龟牛皮兔,10-10 极端令人惊异的网格块益智世界游戏"
},
"multiFeatures": {}
}
s = 'ICBC CNCB PSBC'
for i in s.split(' '):
dic = {"tag20": 0, "tag21": 0, "tag22": 1, "tag23": 1, "tag24": 0, "tag25": 1, "tag26": 0, "tag27": 0, "tag17": 0,
"bank_code": "BCOM", "tag30": 0, "tag8": 0, "tag31": 1, "tag10": 0, "tag32": 0, "tag9": 0,
}
dic['bank_code'] = i
new_d = {}
new_d[str(i)] = dic
test_data['multiFeatures'].update(new_d)
print(test_data)
最后
以上就是无情早晨为你收集整理的Python字典Update()函数及一次bug解决的全部内容,希望文章能够帮你解决Python字典Update()函数及一次bug解决所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复