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

2024-04-19 16:18:26 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我目前在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函数时,它无法打印group:carbs、group:甜点或group:vegies。相反,我得到下面的输出。你知道吗

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

我是否跳过了递归中绕过打印组和相应值的内容?你知道吗


Tags: namenonefoodgroupcssomethingdinnereurope
1条回答
网友
1楼 · 发布于 2024-04-19 16:18:26

docs

The return statement returns with a value from a function. return without an expression argument returns None. Falling off the end of a function also returns None.

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

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)

相关问题 更多 >