【问题标题】:Searching and Filtering in a list of dictionaries/nested dictionary python在字典列表/嵌套字典python中搜索和过滤
【发布时间】:2021-11-21 12:50:16
【问题描述】:

您好,我无法过滤此词典列表。我试图到达的是 all_assets 列表中的 'attributes' 字典并通过(例如)Background: Star 的值对其进行过滤。我目前的尝试是使用 filter() 和 lambda 函数。

到目前为止,我所拥有的是:

all_assets = [{'dateListed': 58391,
  'id': '118572',
  'metadata': {'files': [],
               'mediaType': 'image/png',
               'name': 'The three',
               'tags': [{'right': '101 Galaxy'},
                        {'attributes': {'Background': 'Mars',
                                        'Body': 'Rough',
                                        'Face': 'Dumb',
                                        'Headwear': 'Helmet'}}],
               'thumbnail': 'something'},
  'Session': None,
  'police': 'pewpew',
  'verified': {'project': 'Thes', 'verified': True}},
 {'dateListed': 430298239,
  'id': '1191281',
  'metadata': {'files': [],
               'mediaType': 'image/png',
               'name': 'TheOne',
               'tags': [{'right': '101 Galaxy'},
                        {'attributes': {'Background': 'Star',
                                        'Body': 'Smooth',
                                        'Face': 'Fresh',
                                        'Headwear': 'Cap'}}],
               'thumbnail': 'something'},
  'Session': None,
  'police': 'pewpew',
  'verified': {'project': 'Thes', 'verified': True}}]

search_attribute = 'Background'
search_attribute_value = 'Star'

filtered = filter(lambda i: any(d.get(search_attribute, 'xxx') == search_attribute_value for d in i['metadata']['tags']['attributes']), all_assets)
# print(list(filtered))

输出应该是因为搜索属性是星号:

 {'dateListed': 430298239,
  'id': '1191281',
  'metadata': {'files': [],
               'mediaType': 'image/png',
               'name': 'TheOne',
               'tags': [{'right': '101 Galaxy'},
                        {'attributes': {'Background': 'Star',
                                        'Body': 'Smooth',
                                        'Face': 'Fresh',
                                        'Headwear': 'Cap'}}],
               'thumbnail': 'something'},
  'Session': None,
  'police': 'pewpew',
  'verified': {'project': 'Thes', 'verified': True}}]

那么我想要对过滤后的列表做的是打印出一些值 比如“id”、“name”和“headwear”。

    for x in filtered:
        id = (x.get('id'))
        name = (x.get('metadata')('name'))
        headwear = (x.get('metadata')('tags')('attributes')('Headwear'))
        print(f'ID: {id}')
        print(f'Name: {name}')
        print(f'Headwear: {headwear}')

我试图得到这个输出:

ID: 1191281
Name: TheOne
Headwear: Cap

我对 python 的这个领域有些陌生,因为我只知道一点 lambda 函数。很抱歉,如果它是一个愚蠢的问题或什么的。

【问题讨论】:

    标签: python list dictionary lambda generator-expression


    【解决方案1】:

    我编写了一个自定义过滤方法:

    def customFilter(all_assets, search_attribute, search_attribute_value):
        res = []
        for asset in all_assets:
            if asset:
                attributes = asset["metadata"]["tags"][1]["attributes"]
                if attributes and search_attribute in attributes:
                    if search_attribute_value == attributes[search_attribute]:
                        res.append(asset)
        return res
    

    让我们测试一下:

    all_assets = [
        {
            "dateListed": 58391,
            "id": "118572",
            "metadata": {
                "files": [],
                "mediaType": "image/png",
                "name": "The three",
                "tags": [
                    {"right": "101 Galaxy"},
                    {
                        "attributes": {
                            "Background": "Mars",
                            "Body": "Rough",
                            "Face": "Dumb",
                            "Headwear": "Helmet",
                        }
                    },
                ],
                "thumbnail": "something",
            },
            "Session": None,
            "police": "pewpew",
            "verified": {"project": "Thes", "verified": True},
        },
        {
            "dateListed": 430298239,
            "id": "1191281",
            "metadata": {
                "files": [],
                "mediaType": "image/png",
                "name": "TheOne",
                "tags": [
                    {"right": "101 Galaxy"},
                    {
                        "attributes": {
                            "Background": "Star",
                            "Body": "Smooth",
                            "Face": "Fresh",
                            "Headwear": "Cap",
                        }
                    },
                ],
                "thumbnail": "something",
            },
            "Session": None,
            "police": "pewpew",
            "verified": {"project": "Thes", "verified": True},
        },
    ]
    
    search_attribute = "Background"
    search_attribute_value = "Star"
    
    print(customFilter(all_assets, search_attribute, search_attribute_value))
    

    输出:

    [{'dateListed': 430298239, 'id': '1191281', 'metadata': {'files': [], 'mediaType': 'image/png', 'name': 'TheOne', 'tags': [{'right': '101 Galaxy'}, {'attributes': {'Background': 'Star', 'Body': 'Smooth', 'Face': 'Fresh', 'Headwear': 'Cap'}}], 'thumbnail': 'something'}, 'Session': None, 'police': 'pewpew', 'verified': {'project': 'Thes', 'verified': True}}]
    

    【讨论】:

    • 哇,这个功能非常完美。谢谢。
    • @KeenEm 我没有发现属性在列表中;使用它(在这种情况下使用列表组合没有意义)。我会删除我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 2021-09-19
    • 2011-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多