#๐Ÿ”’ How can I sort a dictionary from the values in the key?

15 messages ยท Page 1 of 1 (latest)

young jacinth
#

Hey, so I have a dictionary
{'Century Park': [1442.28, 490376.02, 2], 'Mill Woods': [1450.75, 482257.75, 4], 'Strathcona': [1447.04, 549875.98, 2], 'Clareview': [1230.12, 452684.16, 6], 'Downtown': [1436.14, 586575.18, 6], 'McKernan': [1367.38, 560626.48, 4], 'Bonnie Doon': [1473.92, 505376.79, 6], 'Southgate': [1642.81, 605456.01, 2]}

How would I sort this numerically based on the second value in the list?

grizzled badgerBOT
#

@young jacinth

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

grizzled badgerBOT
#

sorted(iterable, /, *, key=None, reverse=False)```
Return a new sorted list from the items in *iterable*.

Has two optional arguments which must be specified as keyword arguments.

*key* specifies a function of one argument that is used to extract a comparison key from each element in *iterable* (for example, `key=str.lower`). The default value is `None` (compare the elements directly)...
nova elm
#

you'd need to deconstruct and reconstruct the dict

#

for example

#

!e ```py
d = {3: "c", 1: "a", 2: "b"}

e = {
k: d[k]
for k in sorted(d)
}

print(e)

grizzled badgerBOT
nova elm
# grizzled badger

you make key a function that transforms each element into whatever, and then it numerically sorts them all

young jacinth
#

gotcha ok thanks ill try that out

#

!closr

grizzled badgerBOT
#
Did you mean:

!close

young jacinth
#

!close

grizzled badgerBOT
#
Python help channel closed with !close

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.