【问题标题】:Convert list of dicts to string将字典列表转换为字符串
【发布时间】:2011-07-12 08:17:30
【问题描述】:

我对 Python 很陌生,如果这比我想象的容易,请原谅我。

我收到了一个字典列表,如下所示:

[{'directMember': 'true', 'memberType': 'User', 'memberId': 'address1@example.com'},  
 {'directMember': 'true', 'memberType': 'User', 'memberId': 'address2@example.com'},  
 {'directMember': 'true', 'memberType': 'User', 'memberId': 'address3@example.com'}]

我想生成一个简单的memberId字符串,比如

address1@example.com, 地址2@example.com, 地址3@example.com

但是我尝试过的每种将列表转换为字符串的方法都失败了,因为涉及到字典。

有什么建议吗?

【问题讨论】:

    标签: python string list dictionary


    【解决方案1】:

    这些单线是可以的,但初学者可能不明白。在这里它们被分解:

    list_of_dicts = (the list you posted)
    

    好的,我们有一个列表,其中的每个成员都是一个字典。这是list comprehension

    [expr for d in list_of_dicts]
    

    这就像说for d in list_of_dicts ...expr 为每个 d 评估并生成一个新列表。您也可以使用 if 仅选择其中一些,请参阅文档。

    那么,我们想要什么expr?在每个字典 d 中,我们想要与键 'memberId' 对应的值。那是d['memberId']。所以现在列表理解是:

    [d['memberId'] for d in list_of_dicts]
    

    这给了我们一个电子邮件地址列表,现在用逗号将它们放在一起,我们使用join(参见文档):

    ', '.join([d['memberId'] for d in list_of_dicts])
    

    我看到其他海报在join 的参数列表中遗漏了[],它可以工作。必须查一下,我不知道为什么你可以忽略它。 HTH。

    【讨论】:

      【解决方案2】:
      ', '.join(d['memberId'] for d in my_list)
      

      既然你说你是 Python 新手,我将解释它是如何工作的。

      str.join() 方法结合了可迭代对象(如列表)的每个元素,并使用调用该方法的字符串作为分隔符。

      提供给该方法的可迭代对象是生成器表达式(d['memberId'] for d in my_list)。这实际上为您提供了列表理解 [d['memberId'] for d in my_list] 创建的列表中的每个元素,而无需实际创建列表。

      【讨论】:

        【解决方案3】:

        访问字典。

        ', '.join(d['memberId'] for d in L)
        

        【讨论】:

          猜你喜欢
          • 2014-05-23
          • 2019-05-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多