Losing elements in python code while creating a di

2019-06-22 13:59发布

问题:

I have some 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.key as key and the object p as its value for each element of pub. Are there some side effect I don't see? Because len(pub_dict) should be the same as len(pub) and it is certainly not here, or am I mistaken?

回答1:

Since you may have several p with the same key then you may use list as value for you key within 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)

Or if it is neccessary for you to uniquely identify each record you may use any combined key like key + any other p propery value



回答2:

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

would have give you light on the problem