3

I'm trying to create something to prove the concept that moving through a maze with your left hand on the wall works, so I've made a python 3.6 turtle program to do it. It's extremely inefficient, I know, I'm a beginner, but my question is; How would one find the name of a dictionary from it's contents.

Here's an example:

place1 = {"coordinates" : (150, 150), "filled_in": False}
place2 = {"coordinates" : (100, 100), "filled_in": True}
place3 = {"coordinates" : (50, 50), "filled_in": True}
turtle position = 50, 50

Essentially, something like this

?["coordinates" : (50, 50), "filled_in" = True

I want to be able to find the dictionary from the value within it, so I can check if it's filled in.

if (dictionary containing value of "coordinates" : (50, 50))["filled_in"] = False:
    do whatever

I understand I've probably formatted everything wrong, but thanks for the help in advance.

MSeifert
  • 145,886
  • 38
  • 333
  • 352
Box Fan
  • 43
  • 7

3 Answers3

3

You could put them all in one dictionary that can be indexed by the coordinate:

place1 = {"coordinates" : (150, 150), "filled_in": False}
place2 = {"coordinates" : (100, 100), "filled_in": True}
place3 = {"coordinates" : (50, 50), "filled_in": True}
places = {p["coordinates"]: p for p in [place1, place2, place3]}

And then just index it:

>>> places[(50, 50)]['filled_in']
True
>>> places[(150, 150)]['filled_in']
False
MSeifert
  • 145,886
  • 38
  • 333
  • 352
  • Really helpful. Now I just face the problem of having 64 dictionaries. As I said, poorly formatted. – Box Fan Sep 05 '17 at 12:23
0

Just check the 'coordinates' key of your dictionaries:

for d in (place1, place2, place3):
    if d['coordinates'] == (50, 50):
        do_something()
Right leg
  • 16,080
  • 7
  • 48
  • 81
0

I will elaborate on @MSeifert's answer. Let's say you have 64 variables like following:

place1, place2, ..., place64

Just replace this:

places = {p["coordinates"]: p for p in [place1, place2, place3]}

With:

places_list = ["place{}".format(num) for num in range(1, 65)]
places64 = eval(str(places_list))
places = {p["coordinates"]: p for p in places64}

That being said, using of eval is a bad practice. Consider loading coordinates from separate file for example.

eugenci
  • 173
  • 1
  • 7
  • Instead of `eval` use `places = [locals()[name] for name in places_list]` That also works and it's less "evil" than `eval`. However, it's also not good practice - I would choose a completely different approach when there are lots of dicts. :) – MSeifert Sep 05 '17 at 13:18