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?
The clear() method removes all items from the dictionary.
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.
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.
You can use the following methods to remove items from a dictionary in Python: The del keyword. The clear() method. The pop() method.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With