社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

martineau Nae

martineau Nae 最近创建的主题
martineau Nae 最近回复了
3 年前
回复了 martineau Nae 创建的主题 » Python递归字典搜索

你可以随心所欲 没有 通过使用 json 标准库中的模块(假设您的数据可以序列化为该格式)。这是因为JSON解码器支持 object_hook 参数,它将在每次遇到字典时调用该函数。

其基本思想是通过这个参数指定一个函数,该函数只“监视”正在解码的内容,并检查它是否有所需的密钥。

我的意思是:

import json

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 lookup(data, key):
    results = []

    def decode_dict(a_dict):
        try:
            results.append(a_dict[key])
        except KeyError:
            pass
        return a_dict

    json_repr = json.dumps(data)  # Convert to JSON format.
    json.loads(json_repr, object_hook=decode_dict)  # Return value ignored.
    return results

from pprint import pprint
pprint(lookup(my_dict, my_key), sort_dicts=False)

打印精美的结果列表:

[[{'id': 'minecraft:amethyst_shard', 'Count': 1}],
 [{'Slot': 0,
   'Count': 1,
   'tag': {'Items': [{'id': 'minecraft:amethyst_shard', 'Count': 1}]},
   'id': 'minecraft:bundle'}],
 [{'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}]]