通过mongo的python字典进行递归迭代

时间:2017-06-07 18:46:33

标签: python mongodb dictionary recursion pymongo

这是我目前在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函数时,它无法打印组:carbs,group:dessert或group:veggies。相反,我得到以下输出。

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 个答案:

答案 0 :(得分:2)

来自docs

  

return语句返回一个函数的值。没有表达式参数的return返回None。从函数末尾开始也会返回None

因为您的recursee没有return语句,即它隐式返回None,所以下一条语句

print recursee(d)

recursee对象作为参数执行d并打印函数输出(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)