繁体   English   中英

使用嵌套键数组过滤掉Python字典值

[英]Filtering out Python Dictionary Values with Array of Nested Keys

我试图从python字典中过滤掉许多值。 根据此处看到的答案:将字典过滤为仅包含某些键 我正在做类似的事情:

new = {k:data[k] for k in FIELDS if k in data}

基本上创建new字典,只关心FIELDS数组中列出的键。 我的数组看起来像:

FIELDS = ["timestamp", "unqiueID",etc...]

但是,如果密钥是嵌套的,该怎么办? IE浏览器['user']['color']

如何向该数组添加嵌套键? 我试过了: [user][color]['user']['color']'user]['color ,它们都不对:)我需要的许多值都是嵌套字段。 如何在此数组中添加嵌套键,并且new = {k:data[k] for k in FIELDS if k in data}位仍然有效,则仍然对new = {k:data[k] for k in FIELDS if k in data}具有new = {k:data[k] for k in FIELDS if k in data}

一种非常简单的方法,可能看起来像下面的样子(它不适用于所有可能性-列表/数组中的对象)。 您只需要指定一种“格式”即可查找嵌套值。

'findValue'将在给定对象中分割searchKey(此处为圆点),如果找到,它将在以下值(假设它是字典/对象)中搜索下一个'sub-key'...

myObj = {
    "foo": "bar",
    "baz": {
        "foo": {
            "bar": True
        }
    }
}

def findValue(obj, searchKey):
    keys = searchKey.split('.')

    for i, subKey in enumerate(keys):
        if subKey in obj:
            if i == len(subKey) -1:
                return obj[subKey]
            else:
                obj = obj[subKey]
        else:
            print("Key not found: %s (%s)" % (subKey, keys))
            return None

res = findValue(myObj, 'foo')
print(res)

res = findValue(myObj, 'baz.foo.bar')
print(res)

res = findValue(myObj, 'cantFind')
print(res)

返回:

bar
True
Key not found: cantFind (cantFind)
None

创建一个递归函数,该函数检查字典键是否具有值或字典。 如果键再次具有字典,则调用函数,直到找到非字典值为止。 找到价值后,只需将其添加到新创建的字典中即可。

希望这可以帮助。

暂无
暂无

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

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