开发者

Convert list of dicts to string

开发者 https://www.devze.com 2023-02-16 01:44 出处:网络
I\'m very new to Python, so forgive me if this is easier than it seems to me. I\'m being presented with a list of dicts as follows:

I'm very new to Python, so forgive me if this is easier than it seems to me.

I'm being presented with a list of dicts as follows:

[{'directMember': 'true', 'memberType': 'User', 'memberId': 'address1@example.com'},  
 开发者_如何转开发{'directMember': 'true', 'memberType': 'User', 'memberId': 'address2@example.com'},  
 {'directMember': 'true', 'memberType': 'User', 'memberId': 'address3@example.com'}]

I would like to generate a simple string of memberIds, such as

address1@example.com, address2@example.com, address3@example.com

but every method of converting a list to a string that I have tried fails because dicts are involved.

Any advice?


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

Since you said you are new to Python, I'll explain how this works.

The str.join() method combines each element of an iterable (like a list), and uses the string that the method is called on as the separator.

The iterable that is provided to the method is the generator expression (d['memberId'] for d in my_list). This essentially gives you each element that would be in the list created by the list comprehension [d['memberId'] for d in my_list] without actually creating the list.


These one-liners are ok but a beginner might not get it. Here they are broken down:

list_of_dicts = (the list you posted)

Ok, we have a list, and each member of it is a dict. Here's a list comprehension:

[expr for d in list_of_dicts]

This is like saying for d in list_of_dicts .... expr is evaluated for each d and a new list is generated. You can also select just some of them with if, see the docs.

So, what expr do we want? In each dict d, we want the value that goes with the key 'memberId'. That's d['memberId']. So now the list comprehension is:

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

This gives us a list of the email addresses, now to put them together with commas, we use join (see the docs):

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

I see the other posters left out the [] inside join's argument list, and it works. Have to look that up, I don't know why you can leave it out. HTH.


Access the dicts.

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

精彩评论

暂无评论...
验证码 换一张
取 消