簡體   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