Python Forum
Turn coordinates in string into a tuple
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Turn coordinates in string into a tuple
#1
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)
Reply
#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.
Reply
#3
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.
Reply
#4
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how to convert tuple value into string mg24 2 2,235 Oct-06-2022, 08:13 AM
Last Post: DeaD_EyE
  [SOLVED] [BeautifulSoup] Why does it turn inserted string's brackets into &lt;/&gt;? Winfried 0 1,451 Sep-03-2022, 11:21 PM
Last Post: Winfried
  [SOLVED] [BeautifulSoup] Turn select() into comma-separated string? Winfried 0 1,087 Aug-19-2022, 08:07 PM
Last Post: Winfried
  TypeError: __str__ returned non-string (type tuple) Anldra12 1 7,323 Apr-13-2021, 07:50 AM
Last Post: Anldra12
  code with no tuple gets : IndexError: tuple index out of range Aggam 4 2,725 Nov-04-2020, 11:26 AM
Last Post: Aggam
  How do i turn my program into a .exe julio2000 1 1,848 Feb-14-2020, 08:18 PM
Last Post: snippsat
  How do I turn a directory of HTML files into one CSV? glittergirl 2 1,748 Sep-21-2019, 05:33 PM
Last Post: glittergirl
  Turn py into exe tester21 4 2,982 Jul-22-2019, 04:31 PM
Last Post: nilamo
  How to get first line of a tuple and the third item in its tuple. Need Help, Anybody? SukhmeetSingh 5 3,117 May-21-2019, 11:39 AM
Last Post: avorane
  Not sure how to turn this into a loop iamgonge 1 2,057 Dec-05-2018, 11:03 PM
Last Post: anandoracledba

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020