-1

I have a list of dicts in Python, lets say:

mylist = [{key1: value1, key2: value2}, {key1: value3, key2: value4}, {key1: value5, key2: 'something else'},]

And I want so sort that list in a predefined order

x = ['something else', value4, value2]

EDIT:

My expected result is

mylist = [{key1: value5, key2: 'something else'}, {key1: value3, key2: value4}, {key1: value1, key2: value2}, ]

So it's basically sorting this list on key2 in order of list x. Sorry for lack of clarity.

All I've found is to sort alphabetically or numerically but not with a special order. Any help is highly appreciated.

Kind regards Oliver

6
  • 1
    what is your "spacial" order ? Commented Jul 26, 2016 at 15:11
  • 1
    please add your desired output ... it is unclear at the moment. Commented Jul 26, 2016 at 15:12
  • What defines the order? What are your sorting by? Is it simply the insertion order of the list entries? Are strings sorted first? Do the same keys belong together in sequential order? The question is very ambiguous as of now! Commented Jul 26, 2016 at 15:16
  • What key should be used for sorting? key1? key2? The one with the lower index in x? Commented Jul 26, 2016 at 15:18
  • It seems some people are having difficulty understanding the question. It seems pretty clear that the dicts should be sorted by the index of their values in x. Something like mylist.sort(key=lambda d:x.index(d[key1])). The only question is which key to use. Commented Jul 26, 2016 at 15:23

2 Answers 2

2

using sorted function can do it. you need key to define the order.

>>> mylist
[{1: 1, 2: 2}, {1: 3, 2: 4}, {1: 5, 2: 'something else'}]
>>> x
['something else', 4, 2]
>>> sorted( mylist, key = lambda item: sum([ x.index(i) if i in x else len(x)  for i in item.values()]) )
[{1: 5, 2: 'something else'}, {1: 3, 2: 4}, {1: 1, 2: 2}]

--update--
if you want to sort by value of second

sorted( mylist, key = lambda item: x.index(item[item.keys()[1]]) )
Sign up to request clarification or add additional context in comments.

Comments

0

You'll probably want some sort of lambda:

>>> l = [1,5,2,6]
>>> sorted(l,cmp=lambda x,y:x-y)
[1,2,5,6]
>>> sorted(l,cmp=lambda x,y:y-x)
[6,5,2,1]

Just modify the lambda to somehow compare two values

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.