Zip Question

Chris Kaynor ckaynor at zindagigames.com
Fri Oct 9 13:17:17 EDT 2009


On Fri, Oct 9, 2009 at 10:10 AM, Stephen Hansen <apt.shansen at gmail.com>wrote:

>
>
> On Fri, Oct 9, 2009 at 10:02 AM, Victor Subervi <victorsubervi at gmail.com>wrote:
>
>> Hi;
>> I have the following code:
>>
>>     elif table[0] == 't': # This is a store subtype table
>>       bits = string.split(table, '0')
>>       sst.append(bits[2])
>>       sstp.append(bits[1])
>>   subtypes = dict(zip(sstp, sst))
>>
>> When I print these out to screen, I get this:
>>
>> sst: ['doctors', 'patient']
>> sstp: ['prescriptions', 'prescriptions']
>> subtypes: {'prescriptions': 'patient'}
>>
>> Why do I only get one item from sst and sstp zipped? Why not both??
>
> I think you have a logic problem that's not shown in that code sample:
>
> >>> sst = ['doctors', 'patient']
> >>> sstp = ['prescriptions', 'prescriptions']
> >>> zip(sst,sstp)
> [('doctors', 'prescriptions'), ('patient', 'prescriptions')]
> >>> dict(zip(sst,sstp))
> {'patient': 'prescriptions', 'doctors': 'prescriptions'}
> >>>
>
> --S
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
The issue is:
 subtypes = dict(zip(sstp, sst))

If you remove the dict, you'll see the following:
[('prescriptions', 'doctors'), ('prescriptions', 'patient')]

When this is converted to a dict, the first element of each tuple is placed
as the dict's key, and the second as the value. This means that you have two
keys of prescriptions, and so the final one happens to be chosen as the
value.

Changing the line:
subtypes = dict(zip(sstp, sst))
to:
subtypes = dict(zip(sst, sstp))
as I believe Stephen misread it to be causes the zip operation to return:
[('doctors', 'prescriptions'), ('patient', 'prescriptions')]
and thus the dict will contain:
{'patient': 'prescriptions', 'doctors': 'prescriptions'}


Chris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091009/cff7c174/attachment.html>


More information about the Python-list mailing list