-1

I have coordinates as keys in dict and want to read them like a normal list when I try to extract them. See example:

testlist = {'[0, 0]': 0, '[1 ,1]': 1}

for tmp in testlist:
   if testlist[tmp] == 1:
      print(tmp[0], tmp[1])

The above example should return

1 1

However it outputs

[ 1

I tried list(tmp) and tmp.split() but neither gave the desired output. There probably exists an easy solution, but I could not find it yet.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Coder
  • 75
  • 6

2 Answers2

3

You can use ast.literal_eval to evaluate the strings when needed, converting them to lists. For example:

import ast

testlist = {'[0, 0]': 0, '[1 ,1]': 1}

for key in testlist:
    if testlist[key] == 1:
        tmp = ast.literal_eval(key)
        print(tmp[0], tmp[1])

This produces the desired result:

1 1

Note that ast.literal_eval is a restricted form of eval that is safe from harmful side effects.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
  • 1
    In this specific case, `json.loads()` might be better. – John Gordon Sep 02 '23 at 00:08
  • 1
    @JohnGordon It depends on where the data is coming from and what other forms it might take. If it's just two-element lists of integers, then `ast.literal_eval` is perfectly fine. – Tom Karzes Sep 02 '23 at 00:11
0

This works without imports:

testlist = {'[0, 0]': 0, '[1 ,1]': 1}

for tmp in testlist:
   if testlist[tmp] == 1:
        test = list(tmp.replace("[", "").replace("]", "").replace(",", "").split())
        print(int(test[0]), int(test[1]))

But there're definitely better solutions lol

Coder
  • 75
  • 6