【问题标题】:Convert a colon separated string to a list - within a list of dictionaries... (Python)将冒号分隔的字符串转换为列表 - 在字典列表中...(Python)
【发布时间】: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


【解决方案1】:

你试试,代码如下,首先我在每个字典中迭代,接下来,我使用iteritems 在字典的每个元素中迭代

products = [{'product': 'car', 'colour': 'blue', 'properties': 'stereo;aircon;magwheels'},
            {'product': 'bus', 'colour': 'red', 'properties': 'microphone;aircon;dvd'},
            {'product': 'motorbike', 'colour': 'black', 'properties': None}]

for dict_product in products:
  for key, val in dict_product.iteritems():
    if val is not None and val.find(";") != -1:
      dict_product[key] = val.split(";")

你得到:

[{'product': 'car', 'color': 'blue', 'properties': ['stereo', 'aircon', 'magwheels']},

{'product': 'bus', 'color': 'red', 'properties': ['microphone', 'aircon', 'dvd']},

{'product': 'motorbike', 'color': 'black', 'properties': None}]

【讨论】:

  • dict 是 Python 内置的,您最好为当前字典使用另一个名称。
【解决方案2】:

如果您事先知道必须为其拆分字典值的键,则可以将这些键作为字符串存储在 set 中:

ok2split = set('properties', 'foo', 'blah')

那么你可以如下进行转换

new = [{k:(d[k].split(';')if(d[k] and k in ok2split)else d[k])for k in d}for d in products]

或者,就地操作,

for d in products:
    for k in d:
        if d[k] and k in ok2split: d[k] = d[k].split(';')

【讨论】:

    【解决方案3】:

    您可以将其作为列表理解中的字典理解:

     [ { key: value and value.split(';') for key, value in product.items() } 
          for product in products ]
    

    请注意,由于值可以是 None 而不是字符串,因此您可以编写 value and value.split(';'),而不仅仅是单独拆分。

    如果您不希望字符串拆分,除非有分号要拆分(对我来说似乎很奇怪,但无论如何),您必须明确地说出来

     [ { key: value.split(';') 
                 if value and ';' in value 
                 else value
         for key, value in product.items() } 
          for product in products ]
    

    您可能希望将值处理分解为一个函数:

     def splitOnSemi(value):
        return (value.split(';') 
                 if value and ';' in value 
                 else value)
    
     [ { key: splitOnSemi(value)
         for key, value in product.items() } 
          for product in products ]
    

    【讨论】:

      猜你喜欢
      • 2017-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-23
      • 2013-02-04
      相关资源
      最近更新 更多