2017-06-07 91 views
0

這是我目前在MongoDB中使用的文檔。通過mongo的python字典進行遞歸迭代

{ 
"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 

我跳過了一些我的遞歸繞過打印組和相應的值嗎?

回答

1

docs

return語句返回從函數的值。 return沒有表達式參數返回None。掉到函數的末尾也會返回None

因爲你recursee沒有return聲明,即它含蓄地返回None,所以下面的語句

print recursee(d) 

d對象作爲參數和打印功能輸出(這是None

執行 recursee

試試

def recursee(d): 
    for k, v in d.items(): 
     if isinstance(v, dict): 
      print "{0} :".format(k) 
      recursee(d) 
     else: 
      print "{0} : {1}".format(k, v)