[英]recursive iteration through python dictionary from mongo
這是我目前在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"
}
}
}
}
}
我使用以下代碼行從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)
但是,當我運行recursee函數時,它無法打印組:碳水化合物,組:甜點或組:蔬菜。 相反,我得到以下輸出。
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
我是否在遞歸中跳過繞過打印組和相應值的內容?
從文檔 :
return
語句從函數返回值。 不帶表達式參數的return
返回None
。 從函數末尾掉落也會返回None
。
因為您的recursee
沒有return
語句,即它隱式返回None
,所以下recursee
語句
print recursee(d)
使用d
對象作為參數執行recursee
並輸出函數輸出(為None
)
嘗試
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.