Python Forum
Sort a list of dictionaries by the only dictionary key - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Sort a list of dictionaries by the only dictionary key (/thread-41001.html)



Sort a list of dictionaries by the only dictionary key - Calab - Oct-27-2023

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?


RE: Sort a list of dictionaries by the only dictionary key - buran - Oct-27-2023

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


RE: Sort a list of dictionaries by the only dictionary key - Calab - Apr-29-2024

Thanks for the answer... For some reason I didn't get a notification that my post had been replied to.