[Tutor] deleting elements of a dictionary (Mats Wichmann)

Sergio Rojas sergio_r at mail.com
Wed May 24 14:10:24 EDT 2017


Having now done a quick check, mydict.pop() is no better for this case.

Here's a simplistic sample that does work:

d = {
100:3,
200:4,
111:5,
222:5,
333:5,
500:6,
}

print "original: ", d

new = {key:value for (key,value) in d.iteritems() if value != 5}

print "new: ", new
===========================

"""
In this case, you ned to specify by hand the entry you
want to delete. In case you want to do it without looking
at the stuff, here is one way paraphrasing
the stackoverflow post
https://stackoverflow.com/questions/20672238/find-dictionary-keys-with-duplicate-values
"""

#
d = {
100:3,
200:4,
111:5,
222:5,
333:5,
500:6,
50:7,
60:7,
}

print ("original: ", d)

rev_multidict = {}
for key, value in d.items():
     rev_multidict.setdefault(value, set()).add(key)
print(rev_multidict)

v = [values for key, values in rev_multidict.items() if len(values) > 1]
print('\t Set of keys with same value ', v)

#[print(i) for element in v for i in list(element)]
[d.pop(i) for element in v for i in list(element)]
print('d with every repeated stuff deleted: ', d)


Sergio
Enhance your #MachineLearning and #BigData skills via #Python #SciPy
1) https://www.packtpub.com/big-data-and-business-intelligence/numerical-and-scientific-computing-scipy-video 
2) https://www.amazon.com/Learning-Numerical-Scientific-Computing-Second/dp/1783987707/


More information about the Tutor mailing list