Python Forum
Sort a list of dictionaries by the only dictionary key
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sort a list of dictionaries by the only dictionary key
#1
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?
Reply
#2
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
Calab likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  list.sort() returning None SmallCoder14 8 602 Mar-19-2024, 09:49 PM
Last Post: SmallCoder14
  Dictionary in a list bashage 2 568 Dec-27-2023, 04:04 PM
Last Post: deanhystad
  filtering a list of dictionary as per given criteria jss 5 698 Dec-23-2023, 08:47 AM
Last Post: Gribouillis
  Access list of dictionaries britesc 4 1,091 Jul-26-2023, 05:00 AM
Last Post: Pedroski55
  How to add list to dictionary? Kull_Khan 3 1,018 Apr-04-2023, 08:35 AM
Last Post: ClaytonMorrison
  check if element is in a list in a dictionary value ambrozote 4 1,991 May-11-2022, 06:05 PM
Last Post: deanhystad
  Dictionary from a list failed, help needed leoahum 7 1,979 Apr-28-2022, 06:59 AM
Last Post: buran
Photo a.sort() == b.sort() all the time 3lnyn0 1 1,328 Apr-19-2022, 06:50 PM
Last Post: Gribouillis
  list sort() function bring backs None CompleteNewb 6 4,150 Mar-26-2022, 03:34 AM
Last Post: Larz60+
  how to assign items from a list to a dictionary CompleteNewb 3 1,594 Mar-19-2022, 01:25 AM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020