MarkS
MarkS

Reputation: 1539

Sort and return dict by specific list value

I found this: Sort keys in dictionary by value in a list in Python

and it is almost what I want. I want to sort exactly as is defined in the above post, i.e., by a specific item in the value list, but I want to return the entire original dictionary sorted by the specified list entry, not a list of the keys.

My last try has failed:

details = {'India': ['New Dehli', 'A'],
           'America': ['Washington DC', 'B'],
           'Japan': ['Tokyo', 'C']
           }

print('Country-Capital List...')
print(details)
print()
temp1 = sorted(details.items(), key=lambda value: details[value][1])
print(temp1)

The error:

{'India': ['New Dehli', 'A'], 'America': ['Washington DC', 'B'], 'Japan': ['Tokyo', 'C']}

Traceback (most recent call last):
  File "C:/Users/Mark/PycharmProjects/main/main.py", line 11, in <module>

    temp1 = sorted(details.items(), key=lambda value: details[value][1])
  File "C:/Users/Mark/PycharmProjects/main/main.py", line 11, in <lambda>
    temp1 = sorted(details.items(), key=lambda value: details[value][1])
TypeError: unhashable type: 'list'

Upvotes: 0

Views: 45

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1125068

You are trying to use the (key, value) pair from the dict.items() sequence as a key. Because value is a list, this fails, as keys must be hashable and lists are not.

Just use the value directly:

temp1 = sorted(details.items(), key=lambda item: item[1][1])

I renamed the lambda argument to item to make it clearer what is being passed in. item[1] is the value from the (key, value) pair, and item[1][1] is the second entry in each list.

Demo:

>>> details = {'India': ['New Dehli', 'A'],
...            'America': ['Washington DC', 'B'],
...            'Japan': ['Tokyo', 'C']
...            }
>>> sorted(details.items(), key=lambda item: item[1][1])
[('India', ['New Dehli', 'A']), ('America', ['Washington DC', 'B']), ('Japan', ['Tokyo', 'C'])]

Upvotes: 1

Related Questions