Ashish Bainade Ashish Bainade - 3 years ago 183
Python Question

Convert a list of strings to a list of single-element sets

I have below list

list_of_dict = [{'flat': ['103'], 'wing': u'C'}, {'flat': ['102', '104'], 'wing': u'B'}, {'flat': ['105'], 'wing': u'D'}]


I wish to convert into

list_of_dict = [{'flat': [{'103'}], 'wing': u'C'}, {'flat': [{'102'}, {'104'}], 'wing': u'B'}, {'flat': [{'105'}], 'wing': u'D'}]


Flat should be list of numbers enclosed in '{ }'

Answer Source

The following does exactly what you want,

list_of_dict = [{'flat': ['103'], 'wing': u'C'}, {'flat': ['102', '104'], 'wing': u'B'}, {'flat': ['105'], 'wing': u'D'}]

for e in list_of_dict:
    e['flat'] = [{x} for x in e['flat']]

print(list_of_dict)

Update: The following code should work based on your comment below,

list_of_dict = [{'flat': ['103'], 'wing': u'C'}, {'flat': ['102', '104'], 'wing': u'B'}, {'flat': ['105'], 'wing': u'D'}]

for e in list_of_dict:
    e['flat'] = ['{'+x+'}' for x in e['flat']]

print(list_of_dict)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download