Python Forum

Full Version: Turn coordinates in string into a tuple
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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)
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.
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.
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