【问题标题】:How to convert the list into a list of dictionaries?如何将列表转换为字典列表?
【发布时间】:2020-10-05 04:34:01
【问题描述】:

我有一个这样的列表。

ls = ['Size:10,color:red,', 'Size:10,color: blue,']

我想把列表转换成这种格式。

[{'Size':'10','color':'red'}, {'Size':'10','color': 'blue'}]

我试过的是:

[dict([pair.split(":", 1)]) for pair in ls]

  # It gave me output like this.

[{'Size': '10,color:red,'}, {'Size': '10,color: blue,'}]

但是如果列表是这样的 ['color:blue,'] 但不能与上面的列表正常工作,则此方法有效。

【问题讨论】:

    标签: python django list dictionary


    【解决方案1】:

    我们可以看到你的列表理解中的for pair in ls 已经值得怀疑,因为ls 的元素不是对的。每个元素实际上都包含一系列对。

    这里需要两个循环,一个用于迭代外部列表,另一个用于在每个值内进行迭代,因为这些值实际上是由多个字段组成的字符串。

    虽然这可以通过嵌套列表理解实现,但如果您将问题分解为更简单的部分而不是试图将其全部放在一行中,它会更容易(并且更具可读性)。

    result = []
    for text in ls:
        d = {}
        pairs = text.strip(",").split(",")
        for pair in pairs:
            key, val = pair.split(":")
            d[key] = val.strip()
        result.append(d)
    

    【讨论】:

      猜你喜欢
      • 2017-04-23
      • 2021-10-13
      • 1970-01-01
      • 2011-07-11
      • 2015-07-23
      • 1970-01-01
      • 2014-01-20
      相关资源
      最近更新 更多