2017-01-23 34 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

对不起,它是递归的,没有嵌套。感谢您的更正 –