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
添加回答
舉報