-3

I have a list of dictionaries. The dictionaries have a key called friends whose value is a list of ids. I want to sort the list of dictionary on the basis of number of ids in the friends list.

users=[{'id': 0, 'name': 'Hero', 'friends': [1, 2]}, 
{'id': 1, 'name': 'Dunn', 'friends': [0, 2, 3]},
{'id': 2, 'name': 'Sue', 'friends': [0, 1, 3]},
{'id': 3, 'name': 'Chi', 'friends': [1, 2, 4]}, 
{'id': 4, 'name': 'Thor', 'friends': [3, 5]}, 
{'id': 5, 'name': 'Clive', 'friends': [4, 6, 7]},
{'id': 6, 'name': 'Hicks', 'friends': [5, 8]}, 
{'id': 7, 'name': 'Devin', 'friends': [5, 8]}, 
{'id': 8, 'name': 'Kate', 'friends': [6, 7, 9]},
{'id': 9, 'name': 'Klein', 'friends': [8]}]

How do i proceed with it?

  • So more friends come first? Please add the expected output. Also it will be nice to see some of what you have done. – Dani Mesejo Jan 17 '19 at 16:46
  • 1
    based on the number of friends they each have? how would you treat folks with the same number of friends? – mauve Jan 17 '19 at 16:46
  • 1
    Possible duplicate of [How do I sort a list of dictionaries by a value of the dictionary?](https://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-a-value-of-the-dictionary) – Olf Jan 17 '19 at 16:48

1 Answers1

1

I believe this is what you meant:

sorted(users, key=lambda d: len(d['friends']))

The list of users is sorted depending on the number of friends. Users with less friends appear first. If two users have the same number of friends, the order in which they appear is random.

Óscar López
  • 232,561
  • 37
  • 312
  • 386