我试图从像mongodb这样的字典中获取数据。
虽然有像
这样的文件{'a': 'b', 'c': ['d', {'e': ['i', {'j': 'h'}]}]}
我希望得到价值' h'来自搜索字符串,例如' c.e.j'正如mongodb会做的那样
> db.cc.findOne({'c.e.j':'h'})
{
"_id" : ObjectId("551e5047342b12656b4edecc"),
"a" : "b",
"c" : [
"d",
{
"e" : [
"i",
{
"j" : "h"
}
]
}
]
}
所以我第一次想到的是我需要为每个列表扩展字典,我已经编码了4个小时,买我认为这对我来说很难。
我的代码的最终版本如下所示:
import types
def extdic(cc):
lst = []
for key in cc:
value = cc[key]
if type(value) == types.DictType:
for _ in extdic(value):
cc[key] = _
lst.append(eval(repr(cc)))
return lst
if type(value) == types.ListType:
#print cc
for _ in value:
cc[key] = _
lst.append(eval(repr(cc)))
#print lst
return lst
else:
return [cc]
def mkdic(cc):
lst = []
if type(cc) == types.ListType:
lst = cc
else:
lst = [cc]
reslst = []
while True:
for _ in lst:
#print _
ext = extdic(_)
#print ext
reslst = reslst + ext
if len(reslst) == len(lst):
break
else:
lst = reslst
reslst = []
return lst
if __name__ == '__main__':
cc = [
{'a': 'b', 'c': ['d', {'e': ['i', 'j']}]},
{'f':['g','h']}
]
cd = {'a': 'b', 'c': {'e': ['i', 'j']}}
ce = {'a': {'b': {'c':{'d':{'e':['f','g']}}}}}
for _ in mkdic(cc):
print _
很遗憾我仍然无法得到我想要的东西
我只得到了' ce'字典工作如
MBA:code cc$ python todic3.py
{'a': {'b': {'c': {'d': {'e': 'f'}}}}}
{'a': {'b': {'c': {'d': {'e': 'g'}}}}}
MBA:code cc$
其他字典结构仍然不是我想要的东西..
MBA:code cc$ python todic3.py
{'a': 'b', 'c': ['d', {'e': ['i', {'j': 'h'}]}]}
{'f': 'g'}
{'f': 'h'}
MBA:code cc$
我想使用像
这样的工具MBA:code cc$ echo "{'a': 'b', 'c': ['d', {'e': ['i', {'j': 'h'}]}]}" | python todic3.py c.e.j
c.e.j: h
MBA:code cc$
请帮助..
非常感谢
答案 0 :(得分:0)
这应该返回指定的值。 'yield from'语句要求您使用Python 3。
不幸的是我无法测试ATM。
编辑:我刚刚测试过它,结果出现了一些重大错误。我修复它们,它现在按预期工作。
def iter_flattened(data):
'''returns a generator that allows iteration over key,value pairs, even if the dictionaries are nested in lists'''
if isinstance(data, dict):
yield from data.items()
elif isinstance(data, list):
for item in data:
yield from iter_flattened(item)
def _find(data, keys):
'''This function searches the given (sub-)tree for the given keys'''
if len(keys) == 0:
return data
for key, value in iter_flattened(data):
if key == keys[0]:
result = _find(value, keys[1:])
else:
result = _find(value, keys)
if result is not None:
return result
return None
def find(data, path):
'''Interface function, that accepts the keys as a string seperated with dots.'''
keys = path.split('.')
return _find(data, keys)
要像这样使用:
data = {'a': 'b', 'c': ['d', {'e': ['i', {'j': 'h'}]}]}
value = find(data, 'c.e.j')
print(value) # --> h