python - 将字典列表转换为字符串

标签 python string list dictionary

我是 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] 创建的列表中的每个元素,而无需实际创建列表。

关于python - 将字典列表转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5253773/

相关文章:

python - 如何修剪字符串 : begin immediately after the first full-stop and end at the last

html - 菜单全宽。列表项共享等宽以获得全宽

python - 如何在Python中调试subprocess.call()?

python - sqlalchemy.exc.ResourceClosedError : This transaction is closed 错误

java - 如何在JAVA中修剪StringBuffer中的空白

javascript - 为什么JS中的字符串替换不能替换所有字符

python - 在 python 中连接列表

R:将 data.frame 转换为带有 data.frame 标签的列表

python - 属性错误 : module 'typing' has no attribute 'GenericMeta'

python - 合并相似的 DataFrame 列和堆栈值