2017-01-23 101 views
2

我想從一個python字典中過濾出一些值。基於這裏看到的答案:Filter dict to contain only certain keys。我做的是這樣的:使用嵌套鍵數組篩選出Python字典值

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}位工作?

+0

難道他們都具有相同的 「深度」? –

+0

沒有一些只有一個深,另外兩個或三個深。 @WillemVanOnsem – HectorOfTroy407

+1

從扁平你的字典開始並壓縮鍵http://stackoverflow.com/questions/6027558/flatten-nested-python-dictionaries-compressingkeys。然後,選擇_contain_任何「FIELDS」標籤的鍵。 – DyZ

回答

1

一個相當簡單的方法,可能看起來像下面的樣子(它不適用於所有可能性 - 列表/數組中的對象)。你只需要指定一個'格式'你想如何查找嵌套值。

'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 
-1

創建一個遞歸函數來檢查字典鍵是否有值或字典。 如果鍵有字典再次調用函數,直到找到非字典值。 當您發現價值時,只需將其添加到您新建立的字典。

希望這會有所幫助。

+0

什麼是_nested函數_? – DyZ

+0

對不起,它是遞歸的,沒有嵌套。感謝您的更正 –