1

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)

Jose Ricardo Bustos M.
  • 8,016
  • 6
  • 40
  • 62
Newboy11
  • 2,778
  • 5
  • 26
  • 40

2 Answers2

1

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)].

Avión
  • 7,963
  • 11
  • 64
  • 105
0

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()?

Community
  • 1
  • 1
Remi Guan
  • 21,506
  • 17
  • 64
  • 87