Python convert key-value pair list to dictionary
I'd like to iterate over this list Show
and return a list of dictionaries for each group. E.g.
I've tried splitting the list by , (comma) and searching it for 'name:'. I can return one field such as name, but am struggling to link to to the email, role, etc. Thanks for any help in advance. asked Jun 7, 2019 at 22:59
Leslie AlldridgeLeslie Alldridge 1,2061 gold badge7 silver badges23 bronze badges 2 Without having to know the number of keys each dict has in advance, you can iterate through the list, split each string into a key and a value by
so that given your sample list stored in
answered Jun 7, 2019 at 23:11
0 I am assuming that your order is always the same, i.e., in groups of 4. The idea is to split the strings using
A list comprehension would look like
answered Jun 7, 2019 at 23:09
SheldoreSheldore 36k6 gold badges46 silver badges61 bronze badges You could do :
answered Jun 7, 2019 at 23:10
Ayoub ZAROUAyoub ZAROU 2,3775 silver badges19 bronze badges If the form of the data in the list is guaranteed to always be the way it is in the question's example, then you can do this:
Output:
answered Jun 7, 2019 at 23:12
DjaouadNMDjaouadNM 21.5k4 gold badges29 silver badges52 bronze badges This solution assumes the size of each group is exactly 4
answered Jun 7, 2019 at 23:23
GZ0GZ0 3,8921 gold badge8 silver badges20 bronze badges How do I convert a list to a dictionary in Python?Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.
How do you convert a list to a keyBy using enumerate() , we can convert a list into a dictionary with index as key and list item as the value. enumerate() will return an enumerate object. We can convert to dict using the dict() constructor.
How do I convert a list to a dictionary key?To convert a list to a dictionary using the same values, you can use the dict. fromkeys() method. To convert two lists into one dictionary, you can use the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a list.
Can you have a list as a key in a dictionary Python?A dictionary or a list cannot be a key. Values, on the other hand, can literally be anything and they can be used more than once.
|