joseph wallberg
joseph wallberg

Reputation: 85

recursive iteration through python dictionary from mongo

This is the document I currently have in 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.

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. 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?

Upvotes: 0

Views: 311

Answers (1)

Azat Ibrakov
Azat Ibrakov

Reputation: 10990

From 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.

Because your recursee has no return statement, i.e. it implicitly returns None, so next statement

print recursee(d)

executes recursee with d object as an argument and prints function output (which is 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)

Upvotes: 2

Related Questions