从嵌套字典中的特定对象获取所有信息

2024-07-04 06:17:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过查看特定键从嵌套字典中获取一组数据。你知道吗

我的嵌套词典如下所示:

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

Tags: texttestiddataindexbyadminversion
2条回答

您可以选择与"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))

希望这能让你朝着正确的方向前进。你知道吗

相关问题 更多 >

    热门问题