在列表中创建字典时,在Python代码中丢失元素? [英] Losing elements in python code while creating a dictionary from a list?

查看:409
本文介绍了在列表中创建字典时,在Python代码中丢失元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 打印length:,len(pub)#length:420 
pub_dict = dict((p.key,p)for p in pub)
printdict:,len(pub_dict)#length:163
/ pre>

如果我明白这个权利,我会收到一个包含属性 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆