3 回答
TA贡献1829条经验 获得超13个赞
另一个解决方案很棒,这是可读性的另一个解决方案:
list_dicts = [{'overall': 5.0,
'vote': 'overall',
'reviewerID': 'AAP7PPBU72QFM'},
{'overall': 3.0,
'vote': '5',
'reviewerID': 'A2E168DTVGE6SV'}]
def fix_key(d, k):
try:
d[k] = int(d[k])
except:
d[k] = 0
def fix(d):
fix_key(d, 'vote')
fix_key(d, 'overall')
return d
list_dicts = [fix(d) for d in list_dicts]
# [{'overall': 5, 'vote': 0, 'reviewerID': 'AAP7PPBU72QFM'}, {'overall': 3, 'vote': 5, 'reviewerID': 'A2E168DTVGE6SV'}]
print(list_dicts)
TA贡献1757条经验 获得超7个赞
def clean_value(x):
try:
return int(x)
except ValueError:
return 0
def clean_list_of_dicts(l):
return [{
k:v if k not in ('overall', 'vote') else clean_value(v) \
for k, v in d.items()
} for d in l]
对您的输入数据进行的测试表明该解决方案有效。
>>> clean_list_of_dicts([{'overall': 5.0,
'vote': 'overall',
'reviewerID': 'AAP7PPBU72QFM'},
{'overall': 3.0,
'vote': '5',
'reviewerID': 'A2E168DTVGE6SV'}
])
给出输出:
[{'overall': 5,
'vote': 0,
'reviewerID': 'AAP7PPBU72QFM'},
{'overall': 3,
'vote': 5,
'reviewerID': 'A2E168DTVGE6SV'}]
TA贡献1785条经验 获得超4个赞
我希望它对你有用,但与函数一起使用会更好
for i in data: i['overall'] =int(i['overall']) i['vote'] = int(i['vote']) if (i['vote']).isdigit() else 0
添加回答
举报