Reputation: 51
Basically I have this:
my_list = [{'a': 1, 'b': 1}, {'c': 1}]
And I want an output like this:
new_list = [['a', 'b'],['c']]
I tried my own code but it just returns this:
['a', 'b', 'c']
Upvotes: 3
Views: 68
Reputation: 5766
You can easily do it like -
my_list = [{'a': 1, 'b': 1}, {'c': 1}]
res = list(map(list,my_list))
print(res)
OUTPUT :
[['a', 'b'], ['c']]
If you don't quite get how the above works, here's a simpler version to do the same -
my_list = [{'a': 1, 'b': 1}, {'c': 1}]
res = []
for dicts in my_list:
res.append(list(dicts))
# The above process is equivalent to the shorthand :
# res = [ list(dicts) for dicts in my_list ]
print(res)
OUTPUT :
[['a', 'b'], ['c']]
Upvotes: 2
Reputation: 15364
Here is a possible solution:
result = [list(d) for d in my_list]
It is basically equivalent to:
result = list(map(list, my_list))
Notice that using list(d.keys())
is equivalent to list(d)
.
As suggested by meowgoesthedog in a comment, be careful with Python versions older than 3.7: keys are not ordered, so you might end up having unsorted values.
Upvotes: 3