Merge List of Dictionaries into a Single List
Question:
I have a list of dictionaries that all follow the same format. I want to alter the list of dictionaries to return just the values from all the objects like so.
[{"name": "Dwight"}, {"name": "Michael"}, {"name": "Jim"}] -> ["Dwight", "Michael", "Jim"]
I realize I can iterate through the list and grab the values from each object, but I was wondering if there’s any easier/built in python way to do it. Any suggestions?
Answers:
You can hardly beat an explicit list comprehension:
[v for d in my_list for v in d.values()]
or maybe you meant
[d['name'] for d in my_list if 'name' in d]
If you mean by iterating through a dictionary and building a list, then you probably meant that you already know to do this:
dictionaries_in_list = [{"name": "Dwight"}, {"name": "Michael"}, {"name": "Jim"}]
list = []
for dictionary in dictionaries_in_list:
list.append(dictionary['name'])
print(list)
This is a legitimate pythonic way to express code. Are you asking for a one-liner instead of a two-liner? @It_is_Chris comment is a valid one-line solution.
dictionaries_in_list = [{"name": "Dwight"}, {"name": "Michael"}, {"name": "Jim"}]
it_is_christ_solution = [d['name'] for d in dictionaries_in_list]
print(it_is_christ_solution)
Both of @YvesgereY’s are valid one-liners, too.
I have a list of dictionaries that all follow the same format. I want to alter the list of dictionaries to return just the values from all the objects like so.
[{"name": "Dwight"}, {"name": "Michael"}, {"name": "Jim"}] -> ["Dwight", "Michael", "Jim"]
I realize I can iterate through the list and grab the values from each object, but I was wondering if there’s any easier/built in python way to do it. Any suggestions?
You can hardly beat an explicit list comprehension:
[v for d in my_list for v in d.values()]
or maybe you meant
[d['name'] for d in my_list if 'name' in d]
If you mean by iterating through a dictionary and building a list, then you probably meant that you already know to do this:
dictionaries_in_list = [{"name": "Dwight"}, {"name": "Michael"}, {"name": "Jim"}]
list = []
for dictionary in dictionaries_in_list:
list.append(dictionary['name'])
print(list)
This is a legitimate pythonic way to express code. Are you asking for a one-liner instead of a two-liner? @It_is_Chris comment is a valid one-line solution.
dictionaries_in_list = [{"name": "Dwight"}, {"name": "Michael"}, {"name": "Jim"}]
it_is_christ_solution = [d['name'] for d in dictionaries_in_list]
print(it_is_christ_solution)
Both of @YvesgereY’s are valid one-liners, too.