Creating new Dictionary to sort Key first and then sort on value

Viewed 45

I understand that are inertion sorted. I am trying to make a new dictionary that sorts alphabetically on the 'Key' and then sorts the values on the last element in the tuple.

Dictionary Currently:

D1 = {'Lakers': [('James','PG',23,2), ('Davis', 'PF', 3, 3), ('Johnson', 'PG', 33, 
1)], 'Pistons': [('Billips', 'PG', 1, 1 ), ('Wallace', 'C', 3, 3)], 'Hawks': 
[('Young', 'PG', 11, 1), ('Collins', 'PF', 3, 2)] }

Dictionary I want:

New_D1 = { 'Hawks':[('Collins', 'PF', 3, 2),('Young', 'PG', 11, 1)], 'Lakers': [('Davis', 'PF', 3, 3),('James','PG',23,2), ('Johnson', 'PG', 33, 1)], 'Pistons': [('Wallace', 'C', 3, 3),('Billips', 'PG', 1, 1 ) ] }

My current Code to Sort is:

New_D1  = dict(sorted(D1.items()))

Which creates a new dictionary (New_D1) and only sorts the Keys. I now need to sort the values in the last element of the list of tuples.

5 Answers

You can do this as a comprehension on top of the sort you're already doing:

>>> {k: sorted(v, key=lambda t: -t[-1]) for k, v in sorted(D1.items())}
{'Hawks': [('Collins', 'PF', 3, 2), ('Young', 'PG', 11, 1)], 'Lakers': [('Davis', 'PF', 3, 3), ('James', 'PG', 23, 2), ('Johnson', 'PG', 33, 1)], 'Pistons': [('Wallace', 'C', 3, 3), ('Billips', 'PG', 1, 1)]}

You need to build a new dict, with insertion by sorting the key, and add the values also sorted

result ={}
for key, val in sorted(D1.items()):
    result[key] = sorted(val, key=lambda x: x[-1], reverse=True)

You can inline the modification, and not use a tierce dict, with dict-comprehension

D1 = {key: sorted(val, key=lambda x: x[-1], reverse=True) for key, val in sorted(D1.items())}

You can use itemgetter

>>> from operator import itemgetter
>>> {k:sorted(v, key=itemgetter(3)) for k,v in New_D1.items()}

{'Hawks': [('Young', 'PG', 11, 1), ('Collins', 'PF', 3, 2)], 
'Lakers': [('Johnson', 'PG', 33, 1), ('James', 'PG', 23, 2), ('Davis', 'PF', 3, 3)], 
'Pistons': [('Billips', 'PG', 1, 1), ('Wallace', 'C', 3, 3)]}
{k: sorted(v, key=lambda x: x[:-1]) for k,v in sorted(D1.items(), key=lambda x: x[0])}

It's real simple, and you don't even need the lambda function proposed above:

{k: sorted(v) for k,v in D1.items()}

This produces the result you're looking for:

{'Lakers': [('Davis', 'PF', 3, 3),
  ('James', 'PG', 23, 2),
  ('Johnson', 'PG', 33, 1)],
 'Pistons': [('Billips', 'PG', 1, 1), ('Wallace', 'C', 3, 3)],
 'Hawks': [('Collins', 'PF', 3, 2), ('Young', 'PG', 11, 1)]}
Related