Sorting a dictionary with lists as values, according to an element from the list
Here is one way to do this:
>>> sorted(myDict.items(), key=lambda e: e[1][2])
[('item2', [8, 2, 3]), ('item1', [7, 1, 9]), ('item3', [9, 3, 11])]
The key
argument of the sorted
function lets you derive a sorting key for each element of the list.
To iterate over the keys/values in this list, you can use something like:
>>> for key, value in sorted(myDict.items(), key=lambda e: e[1][2]):
... print key, value
...
item2 [8, 2, 3]
item1 [7, 1, 9]
item3 [9, 3, 11]
How to sort a dictionary by values which contain lists in python
Sorted in python
Use this code:
sorted(Dict.items(), key=lambda x: x[1][1],reverse=True)
Output:
[('Key4', ['LONG_A', 9]), ('Key3', ['LONG', 7]), ('Key1', ['LONG', 1])]
How do I sort a list of dictionaries by a value of the dictionary?
The sorted()
function takes a key=
parameter
newlist = sorted(list_to_be_sorted, key=lambda d: d['name'])
Alternatively, you can use operator.itemgetter
instead of defining the function yourself
from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name'))
For completeness, add reverse=True
to sort in descending order
newlist = sorted(list_to_be_sorted, key=itemgetter('name'), reverse=True)
Sorting dictionary containing lists
First, you can't sort a dict
because it doesn't have order 1. You can sort it's items however:
sorted(d.items(), key=lambda t: t[1][1])
Should do the trick.
notes
t[1] # => the "value", t[0] is the "key"
t[1][1] # => The second element in the value.
You'll get a list of 2-tuples (where the first element is the key, and the second element is the value). Of course, you could always pass this list of 2-tuples directly to collections.OrderedDict
if you wanted to construct a dict which has an ordering after the fact ...
1More correctly, the order is arbitrary and could change based on key insertions, deletions, python implementation or version ... (which is why it's easier to say that dict's are unordered)
sorting dictionary with list value (python)
You should not name a Python variable dict
. I will call the dict d
instead.
$ python
Python 3.8.6 (default, Jan 27 2021, 15:42:20)
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> d = {"a":[1,2,3,12],"b":[5,6,7,8],"c":[9,10,11,4]}
This yields a sorted list of the dict items:
>>> sorted(list(d.items()), key=lambda x: x[1][3])
[('c', [9, 10, 11, 4]), ('b', [5, 6, 7, 8]), ('a', [1, 2, 3, 12])]
Now we can get the sorted dict:
>>> dict(sorted(list(d.items()), key=lambda x: x[1][3]))
{'c': [9, 10, 11, 4], 'b': [5, 6, 7, 8], 'a': [1, 2, 3, 12]}
How do I sort a dictionary by value?
Python 3.7+ or CPython 3.6
Dicts preserve insertion order in Python 3.7+. Same in CPython 3.6, but it's an implementation detail.
>>> x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
>>> {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
or
>>> dict(sorted(x.items(), key=lambda item: item[1]))
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
Older Python
It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.
For instance,
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
sorted_x
will be a list of tuples sorted by the second element in each tuple. dict(sorted_x) == x
.
And for those wishing to sort on keys instead of values:
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))
In Python3 since unpacking is not allowed we can use
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=lambda kv: kv[1])
If you want the output as a dict, you can use collections.OrderedDict
:
import collections
sorted_dict = collections.OrderedDict(sorted_x)
Sort list of dictionaries according to the list of values
list_dict.sort(key=lambda x:a_list.index(x['a']))
Sorting dictionary of lists based on first value in list
Did you test what you already had to see whether it still worked? Because it does. When you sort a group of sequences, they are compared "alphabetically" - if the first items of two sequences are equal, their second items are compared, and so on. This means that, in your example, sorted
would compare the first element of the value's list
. If they are different, the sort order is exactly what it would be if you were comparing the first element only with v[0]
. If they are the same, sorting by v[0]
would simply ensure an arbitrary order for those elements. Leaving it as (v,k)
ensures that if the first elements of the value list
are equal, it sorts based on the rest of the elements. If there are two values with identical list
s, it sorts based on the key.
>>> import collections
>>> d = {'key1': [2, 3], 'key2': [7, 7], 'key3': [5, 10]}
>>> orderedDict = collections.OrderedDict(sorted(d.iteritems(), key=lambda (k,v):(v,k), reverse=True))
>>> orderedDict
OrderedDict([('key2', [7, 7]), ('key3', [5, 10]), ('key1', [2, 3])])
Related Topics
Activating Anaconda Environment in VScode
How to Copy Inmemoryuploadedfile Object to Disk
What Is the Best Approach to Change Primary Keys in an Existing Django App
How to Find the First Key in a Dictionary
Sampling Uniformly Distributed Random Points Inside a Spherical Volume
I Have Python on My Ubuntu System, But Gcc Can't Find Python.H
Browse Files and Subfolders in Python
How to Change Foreignkey Display Text in the Django Admin
Filedialog, Tkinter and Opening Files
"Private" (Implementation) Class in Python
Pycharm Import External Library
How to Force/Ensure Class Attributes Are a Specific Type
How to Execute a Group by ... Count or Sum in Django Orm
Replace String Within File Contents
Removing Control Characters from a String in Python
Concat Dataframe Reindexing Only Valid with Uniquely Valued Index Objects