从列表中创建字典时丢失python代码中的元素?

Auf*_*ind 5 python dictionary list-comprehension

我对这个python代码感到头疼.

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

如果我理解这一点,我会得到一个字典,其中包含属性p.key作为键,对象p作为其每个元素的值pub.我有没有看到一些副作用?因为len(pub_dict)应该是相同的len(pub),它肯定不在这里,或者我错了?

Art*_*nka 4

由于您可能有多个具有相同键的 p,因此您可以使用 list 作为新字典中键的值:

pub_dict = {}    
for p in pub:
   if not p.key in pub_dict:
      pub_dict[p.key] = []
   pub_dict[p.key].append(p)
Run Code Online (Sandbox Code Playgroud)

或者,如果您需要唯一地标识每个记录,您可以使用任何组合键,例如 key + 任何其他 p 属性值