Reputation: 425
So I have a huge list of dictionaries and I want to:
(this is only a portion of the list)
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'}]
I tried this code but nothing happened, any help is very appreciated!
Also pandas
library is not allowed for this assignment.
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)
Upvotes: 0
Views: 8849
Reputation: 1780
Assuming you're using Python 3 try this. For Python 2.x the main difference is to use iteritems()
instead of items()
but the rest should remain the same.
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
Upvotes: 1
Reputation: 989
I guess this is what you want.
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
Changes explained:
int(4)
or int(0)
is unneccessary. value == int(value)
does nothing, i.e, it doesn't update your list or dictionary.for name, datalist in clean_data.iteritems():
name is unused and also this does not help to update your list.try
and except:
is used because string value such as Australia
cannot be converted to int
type.Upvotes: 0