Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #72044

Re: Loop thru the dictionary with tuples

From Ned Batchelder <ned@nedbatchelder.com>
Subject Re: Loop thru the dictionary with tuples
Date 2014-05-25 22:13 -0400
References <CA+FnnTwpQKTyvROYq32YsDfwDooDXRbRg-SYGGhFs1T1D9o_Ow@mail.gmail.com> <llsstb$1sa$1@ger.gmane.org> <llu7ni$dph$1@ger.gmane.org>
Newsgroups comp.lang.python
Message-ID <mailman.10326.1401070507.18130.python-list@python.org> (permalink)

Show all headers | View raw


On 5/25/14 10:09 PM, Dave Angel wrote:
> Ned Batchelder <ned@nedbatchelder.com> Wrote in message:
>> On 5/25/14 8:55 AM, Igor Korot wrote:
>>> Hi, ALL,
>>> I have a following data structure:
>>>
>>> my_dict[(var1,var2,var3)] = None
>>> my_dict[(var4,var5,var6)] = 'abc'
>>>
>>> What I'm trying to do is this:
>>>
>>> for (key,value) in my_dict:
>>>       #Do some stuff
>>>
>>> but I'm getting an error "Too many values to unpack".
>>>
>>> What am I doing wrong?
>>>
>>> Thank you.
>>>
>>
>> You want:
>>
>>       for key, value in my_dict.items():  # or .iteritems()
>>
>> Iterating over a dictionary gives you its keys.  items() will give you
>> key,value pairs.
>
>
> Or, if the dict is large,  you might want
>
> for key in my_dict:
>      value = my_dict [key]
>      ...

For a large dict, .iteritems (Python 2) or .items (Python 3) are 
perfectly fine and don't have a cost to avoid.   .items (Python 2) 
produces a list, which would be bad.

-- 
Ned Batchelder, http://nedbatchelder.com

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Loop thru the dictionary with tuples Ned Batchelder <ned@nedbatchelder.com> - 2014-05-25 22:13 -0400

csiph-web