简体   繁体   中英

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 '{ }'

Assuming you want lists of single-element sets, you can use a for loop:

for d in list_of_dict:
     if 'flat' in d:
         d['flat'] = list(map(lambda x: set([x]), d['flat']))

The if check here provides an added level of safety, in case your dictionaries do not contain flat as a key. Alternatively, using the EAFP approach, you may use a try-except brace:

for d in list_of_dict:
     try:
         d['flat'] = list(map(lambda x: set([x]), d['flat']))
     except KeyError: 
         pass

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

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)

A {} denotes a set . Assuming this is what you want, you could do like this:

for x in list_of_dict:
    x['flat'] = Set(x['flat'])

this will edit the list_of_dict to this:

[{'flat': Set(['103']), 'wing': u'C'}, {'flat': Set(['102', '104']), 'wing': u'B'}, {'flat': Set(['105']), 'wing': u'D'}]

If you type {'103'} in your Python interpreter, it will give you this back:

set(['103'])

This is why I assumed you needed sets.

Comprehension that will do what you need as well:

list_of_dict = [{'flat': ['103'], 'wing': u'C'}, {'flat': ['102', '104'], 'wing': u'B'}, {'flat': ['105'], 'wing': u'D'}]
result  = [{k: ['{}{}{}'.format('{',item,'}') for item in v] if k=='flat' else v for k, v in d.items()} for d in list_of_dict]
#[{'flat': ['{103}'], 'wing': u'C'}, {'flat': ['{102}', '{104}'], 'wing': u'B'}, {'flat': ['{105}'], 'wing': u'D'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM