Python Forum
Turn coordinates in string into a tuple - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Turn coordinates in string into a tuple (/thread-27529.html)



Turn coordinates in string into a tuple - Kolterdyx - Jun-09-2020

I have a dict that stores chunk coordinates and their content in a game I'm making. It looks like this


chunks = {
'0,0' : <content>,
'0,1' : <content>
...
}
What I need is to get the keys, and turn them into coordinates, so I get a tuple like this:

'0,0' -> (0, 0)

Is there any way I can acomplish that?

I worked it out, it actually was pretty simple:
a = '1,2'.split(',')
a = tuple(a)
a = (int(a[0]), int(a[1]))
print(a)
Output:
(1, 2)



RE: Turn coordinates in string into a tuple - micseydel - Jun-09-2020

Thanks for posting back your solution! You can do it in one line too
print(tuple(int(x) for x in '1,2'.split(',')))
or
print(tuple(map(int, '1,2'.split(','))))
Personally I prefer the first in Python, since comprehensions are more common than using things like map.


RE: Turn coordinates in string into a tuple - deanhystad - Jun-10-2020

Or you could save all you settings to a JSON file and not have to do any conversion at all. It might be worth investigating.


RE: Turn coordinates in string into a tuple - buran - Jun-10-2020

this looks like XY problem: You have a dict and use str as key. why not use a tuple as key in dict in the first place?
chunks = {
(0, 0): <content>,
(0, 1): <content>
...
}
and because these are coordinates, you can go a step further and use namedtuple