我有以下列表
list_of_dict = [{'flat': ['103'], 'wing': u'C'}, {'flat': ['102', '104'], 'wing': u'B'}, {'flat': ['105'], 'wing': u'D'}]
我希望转换成
list_of_dict = [{'flat': [{'103'}], 'wing': u'C'}, {'flat': [{'102'}, {'104'}], 'wing': u'B'}, {'flat': [{'105'}], 'wing': u'D'}]
Flat应该是“{}”
中包含的数字列表答案 0 :(得分:2)
假设您需要单元素集列表,可以使用for
循环:
for d in list_of_dict:
if 'flat' in d:
d['flat'] = list(map(lambda x: set([x]), d['flat']))
此处的if
检查可提供更高级别的安全性,以防您的词典不包含flat
作为密钥。或者,使用EAFP方法,您可以使用try-except
大括号:
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'}]
答案 1 :(得分:1)
以下内容完全符合您的要求,
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)
<强>更新强> 以下代码应根据您在下面的评论工作
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)
答案 2 :(得分:0)
{}
表示set。假设这是你想要的,你可以这样做:
for x in list_of_dict:
x['flat'] = Set(x['flat'])
这会将list_of_dict
编辑为:
[{'flat': Set(['103']), 'wing': u'C'}, {'flat': Set(['102', '104']), 'wing': u'B'}, {'flat': Set(['105']), 'wing': u'D'}]
如果你在Python解释器中输入{'103'}
,它会回复你:
set(['103'])
这就是为什么我认为你需要套装。
答案 3 :(得分:0)
理解能够满足您的需求:
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'}]