Py学习  »  Python

Python递归字典搜索

Kikugie • 3 年前 • 1368 次点击  

我试图创建一个函数,该函数将嵌套数组(dict/list以任何顺序)和一个键名作为参数,并在列表中返回该键的所有值。

my_key = "Items"

my_dict = [{'z': 0, 'x': 0, 'y': 0, 'Items': [{'Slot': 1, 'id': 'minecraft:rail', 'Count': 1}, {'Slot': 2, 'id': 'minecraft:white_shulker_box', 'tag': {'BlockEntityTag': {'id': 'minecraft:shulker_box', 'Items': [{'Slot': 0, 'Count': 1, 'tag': {'Items': [{'id': 'minecraft:amethyst_shard', 'Count': 1}]}, 'id': 'minecraft:bundle'}]}}, 'Count': 1}]}]

def recursive_lookup(data, key):
    if isinstance(data, list):
        for i in data:
            recursive_lookup(i, key)
    elif isinstance(data, dict):
        for i, v in data.items():
            if i == key:
                print(f'{v = }')
            if isinstance(v, list) or isinstance(v, dict): recursive_lookup(v, key)
print(recursive_lookup(my_dict, my_key))

目前,它会在 print(f'{v = }') .如何将其存储在列表中并作为函数返回传递?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/128830
 
1368 次点击  
文章 [ 3 ]  |  最新文章 3 年前