繁体   English   中英

从嵌套词典中的特定信息获取所有信息

[英]Getting all information from specific in a nested dictionaries

我正在尝试通过查看特定键来从嵌套词典中获取一组数据。

我的嵌套字典如下所示:

dict_items = {
    "base_id": {
        "some-id-C03": {
            "index": 3, 
            "role": "admin", 
            "text": "test_A_02", 
            "data": {
                "comment": "A test", 
                "version": "1", 
                "created": "05/09/18 14:18", 
                "created_by": "John"
            }, 
            "type": "subTesting", 
        }, 
        "some-id-B01": {
            "index": 1, 
            "role": "admin", 
            "text": "test_B_02", 
            "data": {
                "comment": "B test",
                "version": "1", 
                "created": "05/09/18 14:16", 
                "created_by": "Pete"
            }, 
            "type": "subTesting", 
            "id": "33441122-b655-8877-ccddeeff88bb"
        },
        "some-id-A03": {
            "index": 1, 
            "role": "admin", 
            "text": "test_C_01", 
            "data": {
                "comment": "C test",
                "version": "1", 
                "created": "15/06/18 09:12", 
                "created_by": "Pete"
            }, 
            "type": "subTesting", 
            "id": "55667788-c122-8877-zzddff00bb11"
        }
    }
}

虽然我可以使用以下方法执行:

for item in dict_items.get('base_id').values():
    print item['data']['created_date']

我如何分辨/附加我查询过的created_date内的其他信息?

例如,我想获取最新的2条信息(使用datetime模块),在这种情况下,它将向我返回属于密钥的所有信息some-id-C03some-id-B01

这是我期望的输出:

"some-id-C03": {
    "index": 3, 
    "role": "admin", 
    "text": "test_A_02", 
    "data": {
        "comment": "A test", 
        "version": "1", 
        "created": "05/09/18 14:18", 
        "created_by": "John"
    }, 
    "type": "subTesting", 
}, 
"some-id-B01": {
    "index": 1, 
    "role": "admin", 
    "text": "test_B_02", 
    "data": {
        "comment": "B test",
        "version": "1", 
        "created": "05/09/18 14:16", 
        "created_by": "Pete"
    }, 
    "type": "subTesting", 
    "id": "33441122-b655-8877-ccddeeff88bb"
}

您可以将所有与"data"键关联的值,然后根据月份进行排序:

import datetime, re
def _sort_key(d):
  return list(map(int, re.findall('\d+', list(i.values())[0]['data']['created'])))

def get_data(d):
  _c = [[{a:b}] if 'data' in b else get_data(b) for a, b in d.items() if isinstance(b, dict) or 'data' in b]
  return [i for b in _c for i in b]


results = sorted(get_data(dict_items), key=_sort_key)[:2]

输出:

[{'some-id-C03': {'index': 3, 'role': 'admin', 'text': 'test_A_02', 'data': {'comment': 'A test', 'version': '1', 'created': '05/09/18 14:18', 'created_by': 'John'}, 'type': 'subTesting'}}, {'some-id-B01': {'index': 1, 'role': 'admin', 'text': 'test_B_02', 'data': {'comment': 'B test', 'version': '1', 'created': '05/09/18 14:16', 'created_by': 'Pete'}, 'type': 'subTesting', 'id': '33441122-b655-8877-ccddeeff88bb'}}]

如果我理解正确,则希望能够查询此数据结构,以便最终得到与某些条件匹配的所有条目。

我将这样设置:

def query_dict_items(data_dict, condition_fn):
    '''
    Return a list containing the contents of `data_dict` for which 
    `condition_fn` returns `True`.
    '''

    results = []
    for data_item in data_dict['base_id'].values():
        if condition_fn(data_item):
            results.append(data_item)

    return results

然后,您可以定义所需的任何条件。 对于检索在特定日期创建的所有项目的示例:

from datetime import datetime

#   Define a condition function that matches items from Sept 5th, 2018.
sept_5 = datetime.strptime('05/09/18', '%d/%m/%y')
def was_on_sept_5(data_item):
    date_str = data_item['data']['created'].split(' ')[0]
    return datetime.strptime(date_str, '%d/%m/%y').date() == sept_5.date()

#   Print the resulting list.
from pprint import pprint
pprint(query_dict_items(dict_items, was_on_sept_5))

希望这能使您朝正确的方向前进。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM