繁体   English   中英

将字典列表转换为字符串

[英]Convert list of dicts to string

我对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,address2 @ example.com,address3 @ example.com

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

有什么建议吗?

', '.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]的列表[d['memberId'] for d in my_list]创建的列表”中的每个元素,而无需实际创建列表。

这些单线还可以,但初学者可能无法理解。 在这里将它们分解:

list_of_dicts = (the list you posted)

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

[expr for d in list_of_dicts]

这就像for d in list_of_dicts ...所说。 对每个d评估expr并生成一个新列表。 您还可以通过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。

访问字典。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM