Python Forum

Full Version: Sort a list of dictionaries by the only dictionary key
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have the following structure:
my_list = [{"Dog": {"sound":"bark"}}, {"Cow": {"sound":"moo"}}, {"Cat": {"sound":"meow"}}]
I want to get the following from this structure sorted or unsorted:
["Cat", "Cow", "Dog"]
# or
["Dog", "Cow", "Cat"]
The following ALMOST gives me what I want, but I'm getting a list of the complete dictionary instead of just the keys:
sorted(my_list, key=lambda x: x.keys[0])
[{'Cat': {'sound': 'meow'}}, {'Cow': {'sound': 'moo'}}, {'Dog': {'sound': 'bark'}}]
Using Python 2.7, how can I get the list of the first (only) key from each item in my list of dictionaries?
my_list = [{'Cat': {'sound': 'meow'}}, {'Cow': {'sound': 'moo'}}, {'Dog': {'sound': 'bark'}}]
print [d.keys()[0] for d in my_list]
Output:
['Cat', 'Cow', 'Dog']
from itertools import chain
my_list = [{'Cat': {'sound': 'meow'}}, {'Cow': {'sound': 'moo'}}, {'Dog': {'sound': 'bark'}}]
print list(chain(*my_list))
Output:
['Cat', 'Cow', 'Dog']
Both snippets are python2
Thanks for the answer... For some reason I didn't get a notification that my post had been replied to.