从其内容中查找字典

时间:2017-09-05 09:22:29

标签: python dictionary grid maze

我试图创造一些东西来证明用左手在墙上穿过迷宫的概念是有效的,所以我做了一个python 3.6龟程序来做到这一点。这是非常低效的,我知道,我是初学者,但我的问题是; 如何根据它的内容找到字典的名称。

以下是一个例子:

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

基本上,就像这样

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

我希望能够从其中的值中找到字典,因此我可以检查它是否已填写。

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

我知道我可能把所有内容都格式化了错误,但感谢您提前获得的帮助。

3 个答案:

答案 0 :(得分:3)

您可以将它们全部放在一个可以通过坐标索引的字典中:

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]}

然后将其编入索引:

>>> places[(50, 50)]['filled_in']
True
>>> places[(150, 150)]['filled_in']
False

答案 1 :(得分:0)

只需查看词典的'coordinates'键:

for d in (place1, place2, place3):
    if d['coordinates'] == (50, 50):
        do_something()

答案 2 :(得分:0)

我将详细说明@ MSeifert的回答。假设您有64个变量,如下所示:

place1, place2, ..., place64

只需替换它:

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

使用:

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

话虽如此,使用eval is a bad practice。例如,考虑从单独的文件加载坐标。