在列表中创建字典时,在Python代码中丢失元素? [英] Losing elements in python code while creating a dictionary from a list?
问题描述
打印length:,len(pub)#length:420
/ pre>
pub_dict = dict((p.key,p)for p in pub)
printdict:,len(pub_dict)#length:163
如果我明白这个权利,我会收到一个包含属性
p.key
作为关键字的字典,对象p
作为pub
的每个元素的值。有没有一些副作用我看不到?因为len(pub_dict)
应该与len(pub)
相同,这当然不是在这里,还是我错误?解决方案由于您可能有几个p具有相同的密钥,那么您可以使用列表作为新密钥的值:pub_dict = {} pre pre pre pre pre pre pre pre $ p $
pub_dict [p.key] = []
pub_dict [p.key] .append(p)
或者如果您需要唯一标识每个记录,您可以使用任何组合键,如键+任何其他p属性值
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?
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
这篇关于在列表中创建字典时,在Python代码中丢失元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!