【发布时间】:2015-07-12 04:36:21
【问题描述】:
我有来自数据库的数据,该数据库返回的字典列表如下所示:
products = [{'product': 'car', 'colour': 'blue', 'properties': 'stereo;aircon;magwheels'},
{'product': 'bus', 'colour': 'red', 'properties': 'microphone;aircon;dvd'},
{'product': 'motorbike', 'colour': 'black', 'properties': None}]
在它被传递给应用程序使用之前,我想将冒号分隔的字符串转换为一个列表,所以结果是这样的:
[{'product': 'car', 'colour': 'blue', 'properties': ['stereo', 'aircon', 'magwheels']},
{'product': 'bus', 'colour': 'red', 'properties': ['microphone', 'aircon', 'dvd']},
{'product': 'motorbike', 'colour': 'black', 'properties': None}]
我目前正在通过迭代列表中的所有项目并应用以下逻辑来做到这一点:
for product in products:
if product['properties'] is not None:
product['properties'] = product['properties'].split(';')
我必须为字典中的 5 个键执行此操作,所以基本上我重复此逻辑 5 次,每个键一次,如下所示:
for product in products:
if product['properties'] is not None:
product['properties'] = product['properties'].split(';')
if product['blah'] is not None:
product['blah'] = product['blah'].split(';')
if product['foo'] is not None:
product['foo'] = product['foo'].split(';')
有什么更好的方法来做到这一点?
【问题讨论】:
-
澄清一下,需要这个处理的键是一个已知的集合。我不能在所有键上运行拆分,因为存在 a ;这些密钥可以合法存在。
标签: python string list dictionary split