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': '[email protected]'},  
 {'directMember': 'true', 'memberType': 'User', 'memberId': '[email protected]'},  
 {'directMember': 'true', 'memberType': 'User', 'memberId': '[email protected]'}]
I would like to generate a simple string of memberIds, such as
but every method of converting a list to a string that I have tried fails because dicts are involved.
Any advice?
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
To convert a dictionary to string in Python, use the json. dumps() function. The json. dumps() is a built-in function in json library that can be used by importing the json module into the head of the program.
Use the str() and the literal_eval() Function From the ast Library to Convert a Dictionary to a String and Back in Python. This method can be used if the dictionary's length is not too big. The str() method of Python is used to convert a dictionary to its string representation.
', '.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)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With