Simple Dictionary Problem

mackstann mack at incise.org
Mon Aug 25 05:18:26 CEST 2003


On Sun, Aug 24, 2003 at 08:06:56PM -0700, Kris Caselden wrote:
> I'm still new to some of Python's finer details, so this problem is
> probably an easy fix. I can't seem to loop through a dictionary whose
> values are tuples.
> 
> For instance:
> 
> oldlist = {'name':(1,2,3)}
> newlist = []
> for x1,x2 in oldlist:
>     for y1 in x2:
>         newlist.append(str(x1)+str(y1))
> print newlist
> 
> Gives me:
> 
> line 3, in ?
>     for x1,x2 in oldlist:
> ValueError: too many values to unpack
> 
> The docs I've read mention problems where the key is immutable, but
> don't say anything about what data-types are acceptable for the value.
> What am I missing?

When you iterate through a dictionary, you get the keys.  e.g.:

>>> for x,y in {"hi":4}:
...   print x, y
... 
h i

>>> for x in {"hi":4}:
...   print x
... 
hi

So I think what you want to do is:

>>> oldlist = {'name':(1,2,3)}
>>> newlist = []
>>> for x1,x2 in oldlist.items(): # note .items()
...   for y1 in x2:
...     newlist.append(str(x1)+str(y1))
... 
>>> print newlist
['name1', 'name2', 'name3']

Take a look at dict.keys(), dict.values(), and dict.items() (and the
iter- variations: iterkeys, itervalues, iteritems) for varying ways to
loop through a dict.

-- 
m a c k s t a n n  mack @ incise.org  http://incise.org
Real Programs don't use shared text.  Otherwise, how can they use
functions for scratch space after they are finished calling them?





More information about the Python-list mailing list