如何从嵌套字典中按值获取字典键?

How to get a dictionary key by value from a nested dictionary?

我有字典

game_objects = {
    ('wall', 0): {'position': (0, 0), 'passable': False, 'interactable': False, 'char': '#'},
    ('wall', 1): {'position': (0, 1), 'passable': False, 'interactable': False, 'char': '#'},
    ('player',): {'position': (1, 1), 'passable': True, 'interactable': True, 'char': '@', 'coins': 0},
    ('soft_wall', 11): {'position': (1, 4), 'passable': False, 'interactable': True, 'char': '%'}
}

我需要创建一个函数,该函数将从嵌套字典中按值获取字典键。例如:

get_objects_by_coords((0, 1)) == [('wall', 1)]
get_objects_by_coords((1, 1)) == [('player',)]
get_objects_by_coords((2, 1)) == []

这是我所做的:

def get_objects_by_coords(position):
    for position in game_objects.values():
        if position in game_objects.values():
            return game_objects.keys()


print(get_objects_by_coords((0, 0)))

但答案不正确

dict_keys([('wall', 0), ('wall', 1), ('player',), ('soft_wall', 11)])

我只需要这部分

[('wall', 1)]

那么,我该如何改进我的代码?我知道这段代码很糟糕,但我只是在学习

您正在 return 访问每个 dict 密钥,而不是您找到的密钥。我建议您查看 dict.items 方法,其中 return 一对键值。因此,您的函数可能如下所示:

def get_objects_by_coords(game_objects, position):
    for key, value in game_objects.items():
        if position == value.get('position', (None,)):
            return key
get_objects_by_coords(game_objects, (0, 1)) # == ('wall', 1)

此外,如果你要在你的程序中多次迭代字典,我不会像你那样使用数据结构,因为虽然查看 dict 键我 O(1) ,迭代它以获得一个值是 O(n)。此外,我不会使用全局变量(你的函数使用 game_objects 变量,即使它没有将它作为参数接收),因为这不是一个好习惯。

希望这对您有所帮助!祝你好运,编码愉快!

你是这个意思吗?

def get_objects_by_coords(position):
    return [key for key, val in game_objects.items()
                for k, v in val.items() if k == 'position' and v == position]

assert get_objects_by_coords((0, 1)) == [('wall', 1)]
assert get_objects_by_coords((1, 1)) == [('player',)]
assert get_objects_by_coords((2, 1)) == []

也许你的整个结构都是错误的。这个呢?

game_objects =  [
    [
        {
            'type':'wall',
            'item_no':0,
            'passsable':False,
            'interacable':False,
            'char':'#'
        },
        
        {
            'type':'wall',
            'item_no':1,
            'passsable':False,
            'interacable':False,
            'char':'#'
        }
    ],
    [
        {
            'type':'player',
            'item_no':None,
            'passable':True,
            'interactable': True,
            'char': '@',
            'coins': 0
        },
        {
            'type':None
        },
        {
            'type':None
        },
        {
            'type':None
        },
        {
            'type':'soft_wall',
            'item_no': 11,
            'passable': False,
            'interactable': True,
            'char': '%'}
    ],
    
]

输出

game_objects[1][4]

{'type': 'soft_wall',
 'item_no': 11,
 'passable': False,
 'interactable': True,
 'char': '%'}

game_objects[0][1]

{'type': 'wall',
 'item_no': 1,
 'passsable': False,
 'interacable': False,
 'char': '#'}