Losing items in python code when creating a dictionary from a list?

I have a headache with this python code.

    print "length:", len(pub) # length: 420
    pub_dict = dict((p.key, p) for p in pub)
    print "dict:", len(pub_dict) # length: 163

If I understand this right, I get a dictionary containing the attribute p.keyas a key, and the object pis its value for each element pub. Is there a side effect that I don't see? Because it len(pub_dict)should be the same as len(pub), and this, of course, is not here, or am I mistaken?

+5
source share
2 answers

Since you can have multiple p with the same key, you can use the list as the value for the key in the new dicitionary:

pub_dict = {}    
for p in pub:
   if not p.key in pub_dict:
      pub_dict[p.key] = []
   pub_dict[p.key].append(p)

, , , + p

+3
pub_dict = {}
for i,p in enumerate(pub):
     pub_dict[p.key] = p
     print i+1,len(pub_dict)

-1

All Articles