Reputation: 173
Here is list containing dictionary
[{u'alpha2_code': u'AX', u'alpha3_code': u'ALA', u'name': u'\ufffd\ufffdland Islands'},{u'alpha2_code': u'AL', u'alpha3_code': u'ALB',u'name':u'Albania'},{u'alpha2_code':u'DZ',u'alpha3_code': u'DZA', u'name': u'Algeria'},{u'alpha2_code': u'AS', u'alpha3_code': u'ASM', u'name': u'American Samoa'}]
I want to remove 'u
from each key/value pair.
Upvotes: 0
Views: 560
Reputation: 12992
Actually, I don't know why you want to convert your (key, value) pairs into string, but here is a simple solution. In this function, I'm creating a new list and encode each (key, value) pair into an ascii string.
def change_type(lst):
new_list= []
for dic in lst:
new_dic = {}
for k, v in dic.iteritems():
new_dic[k.encode("ascii","ignore")] = v.encode("ascii","ignore")
new_list.append(new_dic)
return new_list
Note that you have a value of "\ufffd\ufffdland Islands"
which contains unicode characters. So, you have to remove these characters and this function should work. Here is how your list should be:
>>> lst = [ {u'alpha2_code': u'AX', u'alpha3_code': u'ALA', u'name': u'land Islands'},
{u'alpha2_code': u'AL', u'alpha3_code': u'ALB', u'name': u'Albania'},
{u'alpha2_code': u'DZ', u'alpha3_code': u'DZA', u'name': u'Algeria'},
{u'alpha2_code': u'AS', u'alpha3_code': u'ASM', u'name': u'American Samoa'}]
>>> new_list = change_type(lst)
>>> new_list
[{'alpha2_code': 'AX', 'alpha3_code': 'ALA', 'name': 'land Islands'},
{'alpha2_code': 'AL', 'alpha3_code': 'ALB', 'name': 'Albania'},
{'alpha2_code': 'DZ', 'alpha3_code': 'DZA', 'name': 'Algeria'},
{'alpha2_code': 'AS', 'alpha3_code': 'ASM', 'name': 'American Samoa'}]
Upvotes: 2