How much slower is dict indexing vs. list indexing?

Paul McGuire ptmcg at austin.rr._bogus_.com
Fri Jan 12 15:40:21 CET 2007


"Emin" <emin.shopper at gmail.com> wrote in message 
news:1168611039.720278.13430 at s34g2000cwa.googlegroups.com...
> On Jan 11, 5:53 pm, Steve Holden <s... at holdenweb.com> wrote:
>>
>> What technique were you thinking of to look up the cached index values
>> in Python, just as a matter of curiosity? Storing them in a dict? It
>> would be hard to think of a faster way ... ;-)
>
> I didn't have anything fancy in mind. I was just wondering whether it
> makes sense to replace a block of code like
>
> data = {'a' : 1, 'b' :2, 'c' : 3}
> for i in someLargeList:
>   for name in ['a','b','c']:
>      result.append(data[name])
>
> with somthing like
>
> data = {'a' : 1, 'b' :2, 'c' : 3}
> dataValues = [data[k] for k in ['a','b','c']
> for i in someLargeList:
>   for index in [0,1,2]:
>      result.append(dataValues[index])
>

[Your as-posted code doesn't run, you are missing a trailing ']' in your 
list comprehension. ]

So what you want is this?
1. Get the values from the data dict in order of their key, ['a','b','c'] 
(which is not the same as getting the data.values() list, which is in 
unpredictable order)
2. For every element in some larger list, append each of the elements in 
order from step 1 to some other result list.

First of all, realize that:
>   for index in [0,1,2]:
>      result.append(dataValues[index])
is the same as
    result.extend(dataValues)
assuming that dataValues has exactly 3 elements in it.

Second, why are you iterating over someLargeList?  You are doing nothing 
with i, and neither the data dict nor the dataValues list changes as you 
iterate.

This will do the job more quickly, I should think:

data = {'a' : 1, 'b' :2, 'c' : 3}
dataValues = [data[k] for k in ['a','b','c']]
result.extend( dataValues * len(someLargeList) )

-- Paul





More information about the Python-list mailing list