[英]recursive iteration through python dictionary from mongo
This is the document I currently have in MongoDB. 这是我目前在MongoDB中拥有的文档。
{
"name":"food",
"core":{
"group":{
"carbs":{
"abbreviation": "Cs"
"USA":{
"breakfast":"potatoes",
"dinner":"pasta"
},
"europe":{
"breakfast":"something",
"dinner":"something big"
}
},
"abbreviation": "Ds"
"dessert":{
"USA":{
"breakfast":"potatoes and eggs",
"dinner":"pasta"
},
"europe":{
"breakfast":"something small",
"dinner":"hello"
}
},
"abbreviation": "Vs"
"veggies":{
"USA":{
"breakfast":"broccoli",
"dinner":"salad"
},
"europe":{
"breakfast":"cheese",
"dinner":"asparagus"
}
}
}
}
}
I extract the data from mongo with the following lines of code. 我使用以下代码行从mongo中提取数据。
data = collection.foodie.find({"name":"food"}, {"name":False, '_id':False})
def recursee(d):
for k, v in d.items():
if isinstance(v,dict):
print recursee(d)
else:
print "{0} : {1}".format(k,v)
However, when i run the recursee function, it fails to print group : carbs, group : dessert, or group : veggies. 但是,当我运行recursee函数时,它无法打印组:碳水化合物,组:甜点或组:蔬菜。 Instead i get the below output.
相反,我得到以下输出。
breakfast : something big
dinner : something
None
abbreviation : Cs
breakfast : potatoes
dinner : pasta
None
None
breakfast : something small
dinner : hello
None
abbreviation : Ds
breakfast : potatoes and eggs
dinner : pasta
None
None
breakfast : cheese
dinner : asparagus
None
abbreviation : Vs
breakfast : broccoli
dinner : salad
Am i skipping something in my recursion that is bypassing printing the group and corresponding value? 我是否在递归中跳过绕过打印组和相应值的内容?
The
return
statement returns with a value from a function.return
语句从函数返回值。return
without an expression argument returnsNone
.不带表达式参数的
return
返回None
。 Falling off the end of a function also returnsNone
.从函数末尾掉落也会返回
None
。
Because your recursee
has no return
statement, ie it implicitly returns None
, so next statement 因为您的
recursee
没有return
语句,即它隐式返回None
,所以下recursee
语句
print recursee(d)
executes recursee
with d
object as an argument and prints function output (which is None
) 使用
d
对象作为参数执行recursee
并输出函数输出(为None
)
Try 尝试
def recursee(d):
for k, v in d.items():
if isinstance(v, dict):
print "{0} :".format(k)
recursee(v)
else:
print "{0} : {1}".format(k, v)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.