1

I have two dictionaries with the same keys but different values. I want to perform an operation that combines the two and then creates a 'list type' object of them in no specific order. I am going to be doing this on large datasets so speed is a priority. What is the fastest way of doing this?

So far I have these ideas. I am new to python so I don't know much about how each function operates but I am assuming option 2 is the fastest. Are there faster methods?

mydict = {"cats":1,"dog":3,"bird":2,"wolves":10}
exp = {"cats":10,"dog":23,"bird":34,"wolves":43}

#Option 1
mydict.update((x, y**(exp[x])) for x, y in mydict.items())
items = mydict.values()

#Option 2          // I think this is currently the fastest
items = []
items.append(y**(exp[x]) for x,y in mydict.items())

#Option 3
items = numpy.array(len(mydict))
for x,y in mydict:
    items[?] = y**(exp[x])     // Is there a way to do this? Maybe with a counter
4

1 回答 1

4

怎么样

[mydict[key]**exp[key] for key in mydict.keys()]

假设 mydict 和 exp 都具有完全相同的键?

边注:

[mydict[key]**exp[key] for key in mydict]

做和上面一样的事情,.keys()是可选的。

如果您关心速度,请使用 time 模块来测试每种方法的速度:

import time
t = time.clock()
for i in range(1000):
    # your code here, for example:
    [mydict[key]**exp[key] for key in mydict.keys()]
print "time", time.clock() - t
于 2013-07-24T22:14:36.813 回答