Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Losing elements in python code while creating a dictionary from a list?

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?

like image 804
Aufwind Avatar asked Jun 05 '11 19:06

Aufwind


People also ask

Which function removes all the elements of a list dictionary?

The clear() method removes all items from the dictionary.

How do I convert a list to a dictionary in Python?

Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.

Which function removes the key value pair from a dictionary?

Using pop() The in-built function pop() deletes a specific key: value pair from a dictionary. The function takes two arguments: key : the key of the value that needs to be deleted.

Can you remove elements from a dictionary in Python?

You can use the following methods to remove items from a dictionary in Python: The del keyword. The clear() method. The pop() method.


1 Answers

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

like image 52
Artsiom Rudzenka Avatar answered Sep 21 '22 12:09

Artsiom Rudzenka