Newboy11
Newboy11

Reputation: 3136

iterate dictionary from a function

I'm having a problem iterating dictionary from a function.

def iteratedic():
    datadic={
    "one" : 1,
    "two" : 2,
    "three" : 3,
    "four" : 4
    }

    return datadic

def getdic():
    dictionary = iteratedic()
    for m, n in dictionary:
        print (m, n)

getdic()

It says

ValueError: too many values to unpack (expected 2)

Upvotes: 1

Views: 86

Answers (2)

Remi Guan
Remi Guan

Reputation: 22282

If we do for i in my_dict, then it will gives the keys, not keys: values. Example:

>>> a = {"one" : 1, "two" : 2, "three" : 3, "four" : 4}
>>> for i in a:
...     print(i)
... 
four
three
two
one

So if you do for i, j in my_dict, then it will raise an error.

You could use dict.items(), it returns a list that saves all keys and values in tuples like this:

>>> a.items()
[('four', 4), ('three', 3), ('two', 2), ('one', 1)]

So you could do...

def getdic():
    dictionary = iteratedic()
    for m, n in dictionary.items():
        print (m, n)

Also, dict.iteritems() is better than dict.items(), it returns a generator(But note that in Python 3.x, dict.iterms() returns a generator and there's no dict.iteritems()).

See also: What is the difference between dict.items() and dict.iteritems()?

Upvotes: 0

Avión
Avión

Reputation: 8386

You have to iterate through the .items():

def iteratedic():
    datadic={
    "one" : 1,
    "two" : 2,
    "three" : 3,
    "four" : 4
    }

    return datadic

def getdic():
    dictionary = iteratedic()
    for m, n in dictionary.items():
        print (m, n)

getdic()

If you print dictionary you'll see that you get {'four': 4, 'three': 3, 'two': 2, 'one': 1} . If you print dictionary.items() you get the list of the items. [('four', 4), ('three', 3), ('two', 2), ('one', 1)].

Upvotes: 1

Related Questions