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])
#๐ how do i sort this dictionary
28 messages ยท Page 1 of 1 (latest)
@harsh robin
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.
Closes after a period of inactivity, or when you send !close.
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
hmm, I think it's much easier not using a dictionary and just storing it as a bunch of tuples in a list
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]))
Hm Iโll give ur idea a go!
!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])))
@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))]
done
oh thank you so much but is there a way where i can
sort this by the y coordinate from highest to lowest
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])))
@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))]
i tried something similar to this before but wasnt sure how to sort it out by the y coordinate
thank you so much
u have no idea how long i have been trying to code this haha
!close
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.