Scott Skiles
Scott Skiles

Reputation: 3857

Sort dictionary by key: single key priority and alphabetical

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?

Upvotes: 1

Views: 284

Answers (1)

Ajax1234
Ajax1234

Reputation: 71461

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}

Upvotes: 6

Related Questions