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

时间:2017-01-23 07:48:48

标签: python arrays dictionary filter

我试图从python字典中过滤掉一些值。根据这里看到的答案:Filter dict to contain only certain keys。我正在做类似的事情:

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

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

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

但是,如果密钥是嵌套的,我该怎么办呢? I.E. ['user']['color']

如何向此数组添加嵌套键?我试过了: [user][color]['user']['color']'user]['color,其中没有一个是正确的:)我需要的许多值都是嵌套字段。如何在此数组中添加嵌套键并使new = {k:data[k] for k in FIELDS if k in data}位仍有效?

2 个答案:

答案 0 :(得分:1)

一种非常简单的方法,可能如下所示(它不适用于所有可能性 - 列表/数组中的对象)。您只需指定一种格式'您希望如何查找嵌套值。

' findValue'将在给定对象中拆分searchKey(此处为点),如果发现它将搜索下一个子键'在以下值中(假设它是一个dict / object)...

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

答案 1 :(得分:-1)

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

希望这有帮助。