所以我有很多字典,我想:
(这只是列表的一部分)
clean_dict= [{'origin': 'Various/Unknown', 'idps': '', 'year': '1951', 'total': '180000', 'stateless': '', 'ret_refugees': '', 'asylum': '', 'country': 'Australia', 'others': '', 'ret_idps': '', 'refugees': '180000'}, {'origin': 'Various/Unknown', 'idps': '', 'year': '1951', 'total': '282000', 'stateless': '', 'ret_refugees': '', 'asylum': '', 'country': 'Austria', 'others': '', 'ret_idps': '', 'refugees': '282000'}]
我试过这段代码但没有任何反应,非常感谢任何帮助!
此作业也不允许使用pandas
库。
for name, datalist in clean_data.iteritems():
for datadict in datalist:
for key, value in datadict.items():
if value == "*":
datadict[key] = int(4)
elif value == "":
datadict[key]= int(0)
else:
value == int(value)
答案 0 :(得分:1)
假设您正在使用Python 3试试这个。对于Python 2.x,主要区别在于使用iteritems()
而不是items()
,但其余部分应保持不变。
for dict in clean_dict:
for k,v in dict.items():
if v == '*':
dict[k] = 4
elif v == '':
dict[k]= 0
else:
# not necessarily an integer so handle exception
try:
dict[k] = int(v)
except ValueError:
pass
答案 1 :(得分:0)
我想这就是你想要的。
clean_dict= [{'origin': 'Various/Unknown', 'idps': '', 'year': '1951', 'total': '180000', 'stateless': '', 'ret_refugees': '', 'asylum': '', 'country': 'Australia', 'others': '', 'ret_idps': '', 'refugees': '180000'}, {'origin': 'Various/Unknown', 'idps': '', 'year': '1951', 'total': '282000', 'stateless': '', 'ret_refugees': '', 'asylum': '', 'country': 'Austria', 'others': '', 'ret_idps': '', 'refugees': '282000'}]
for datadict in clean_dict:
for key, value in datadict.items():
if value == '*':
datadict[key] = 4
elif value == '':
datadict[key] = 0
else:
try:
datadict[key] = int(value)
except:
continue
更改说明:
int(4)
或int(0)
是不必要的。 value == int(value)
什么都不做,即它不会更新您的列表或字典。for name, datalist in clean_data.iteritems():
名称未使用,这也无法更新您的列表。try
和except:
被使用,因为Australia
等字符串值无法转换为int
类型。