让我们拿字典
r = {u' a':' john','':' ABA Design House,开发心灵基金会,食物网南海滩葡萄酒&安培;美食节',你':'给'}
我想将其转换为:
r = {u' a':' john',u' b': [' ABA Design House',&# 39;开发Minds Foundation',' Food Network South Beach Wine&美食节'] ,你':'给'}
答案 0 :(得分:5)
使用内置方法split()
>>> r[u'b'] = r[u'b'].split(',')
>>> r
{u'a': 'john', u'c': 'give', u'b': ['ABA Design House ', ' Developing Minds Foundation ', ' Food Network South Beach Wine & Food Festival']}
如果您对前导/尾随空格感到不舒服,请在拆分后使用strip()方法
>>> r[u'b']=[x.strip() for x in r[u'b'].split(',')]
>>> r
{u'a': 'john', u'c': 'give', u'b': ['ABA Design House', 'Developing Minds Foundation', 'Food Network South Beach Wine & Food Festival']}
答案 1 :(得分:2)
假设您想对字典中每个以逗号分隔的值执行此操作:
for k, v in r.items():
if "," in v:
r[k] = [item.strip() for item in v.split(",")]