Wednesday, August 25, 2010

Dictionary as Generator

What will you do if you are creating dictionary structure dynamically, and it got millions of keys?
Accessing that dictionary later in your code might get some resource. can't it?
I also hanged on this kind of situation and my dictionay got 10K millions key. So i used dictionary as generator to make my work easy.
Folloing code just explain how to use dictionary as generator.

[code]
a=range(100000)
b=range(100000)
c=dict(zip(a,b)) #create dictionary with 100000 keys
d_len=len(c)
d_keys = (k for k in c.keys())   # generator expression
for i in range(d_len):
   key = d_keys.next()
       .
    .
    .
   ## do your operation on keys
[/code]

No comments: