1

I have a Python dictionary d:

d = { 
    'a': 1,
    'b': 2,
    'c': 3,
    'd': 4,
}

I want to sort this such that:

  1. The key with value x is first.
  2. Everything else is sorted alphabetically.

So if x = 'c' then I want the output to be:

>>> print(new_d)
>>> { 'c': 3, 'a': 1, 'b': 2, 'd': 4}

Is there a straightforward / easy / Pythonic way to do this? And yes I have seen and understand the plethora of answers for the questions How do I sort a dictionary by value? and How can I sort a dictionary by key?

Scott Skiles
  • 3,647
  • 6
  • 40
  • 64
  • What did you find unsatisfactory about the answers in the two questions you linked? Or what further information are you looking for? – mypetlion Apr 04 '19 at 15:51
  • I don't know how to sort on this condition! I don't even know how to do it with a lambda... – Scott Skiles Apr 04 '19 at 15:52
  • 1
    (If it is that easy can you answer it? :-) ) – Scott Skiles Apr 04 '19 at 15:53
  • The top answer in the first question you linked to is very clear in explaining that you can't sort a dictionary. If you are using Python 3.6+, you can create a new `dict` that will be ordered by insertion order. Or you could use the `OrderedDict`. – mypetlion Apr 04 '19 at 15:56

1 Answers1

6

Dictionaries pre Python 3.7 are not sorted, however, you can sort the list of tuples garnered from dict.items, and if you are using Python 3.7, create a dict from the result. The lambda sort key returns a list with two elements. The first element is the result of the key comparison, in this case, x == 'c', while the second element is the numerical value associated with the key:

d = {'a': 1, 'b': 2, 'c': 3, 'd': 4} 
x = 'c'
new_d = sorted(d.items(), key=lambda c:[c[0] != x, c[-1]])

Output:

[('c', 3), ('a', 1), ('b', 2), ('d', 4)]

In Python 3.7:

print(dict(new_d))

Output:

{'c': 3, 'a': 1, 'b': 2, 'd': 4}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102