#๐Ÿ”’ how do i sort this dictionary

28 messages ยท Page 1 of 1 (latest)

harsh robin
#
for d_pos in all_d_pos:
    distance = math.dist(d_pos, x_pos)
    if distance not in my_dic:
        my_dic[distance] = [d_pos]
    else:
        my_dic[distance].append(d_pos)```
dictionary: {1.4142135623730951: [(1, 0), (1, 2)], 1.0: [(1, 1)]}

I want to sort this dictionary by their key first (lowest to highest) and IF they have two or more values that are the same key then I want to sort it by their y coordinate ([x, y])
fading needleBOT
#

@harsh robin

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.

harsh robin
#

if anyone can help would be greatly appreciated

#

my expected output should be
dictionary: {1.0: [(1, 1)], 1.4142135623730951: [(1, 2), (1, 0)]}
but im not sure how to do so

torn juniper
#

so the one-liner should almost work
sorted((math.dist(d_pos, x_pos), d_pos) for d_pos in all_d_pos)

#

the problem is that it sorts x before y

#

so just specify the key

#

sorted((math.dist(d_pos, x_pos), d_pos) for d_pos in all_d_pos, key=lambda x: (x[0], x[1][1]))

harsh robin
#

Hm Iโ€™ll give ur idea a go!

torn juniper
#

!e

import math
x_pos=(0, 1)
all_d_pos=[(1, 0), (1, 2), (1, 1)]
print(sorted(((math.dist(d_pos, x_pos), d_pos) for d_pos in all_d_pos), key=lambda x: (x[0], x[1][1])))
fading needleBOT
#

@torn juniper :white_check_mark: Your 3.12 eval job has completed with return code 0.

[(1.0, (1, 1)), (1.4142135623730951, (1, 0)), (1.4142135623730951, (1, 2))]
torn juniper
#

done

harsh robin
#

oh thank you so much but is there a way where i can

#

sort this by the y coordinate from highest to lowest

torn juniper
#

yeah, change the key

#

!e

import math
x_pos=(0, 1)
all_d_pos=[(1, 0), (1, 2), (1, 1)]
print(sorted(((math.dist(d_pos, x_pos), d_pos) for d_pos in all_d_pos), key=lambda x: (x[0], -x[1][1])))
fading needleBOT
#

@torn juniper :white_check_mark: Your 3.12 eval job has completed with return code 0.

[(1.0, (1, 1)), (1.4142135623730951, (1, 2)), (1.4142135623730951, (1, 0))]
harsh robin
#

OHH

#

THANK YOU A TON

#

you save me a whole chunk of time

#

i get it now

harsh robin
#

thank you so much

#

u have no idea how long i have been trying to code this haha

#

!close

fading needleBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, 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.