[英]replace values in list of python dictionaries
所以我有很多词典,我想:
(这只是列表的一部分)
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)
假设您使用的是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
我想这就是你想要的。
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
类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.