Reputation: 31
I wanted to know how to delete an element from a dictionary, but I am going directly to my case. For example, I have a dictionary like this one
dic = {(0, 0, 255): [(255, 255, 0), (0, 255, 255)],
(255, 0, 0): [(0, 0, 255), (0, 255, 0), (255, 255, 0), (0, 255, 255)],
(0, 255, 0): [(0, 0, 255), (255, 255, 0), (0, 255, 255)],
(255, 255, 0): [],
(0, 255, 255): [(255, 255, 0)]}
My purpose is to delete the key that corresponds to the empty list, that here is (255, 255, 0): [] but I would also like to delete the following tuple (i.e. the key) in all other cases where it is present in the dictionary (therefore as a value). So I would like to get to have this:
dic = {(0, 0, 255): [(0, 255, 255)],
(255, 0, 0): [(0, 0, 255), (0, 255, 0), (0, 255, 255)],
(0, 255, 0): [(0, 0, 255), (0, 255, 255)],
(0, 255, 255): []}
I want to specify the fact that I save each deleted key in a list, in fact I used this to be able to delete from the dictionary every key that had an empty list as a value, but I cannot then take the deleted value and delete it from the whole dictionary How can I do this?
Upvotes: 1
Views: 96
Reputation: 559
To delete a key-value pair from a dictionary just del dictionary[key]
Updated:
In your case:
dic = {(0, 0, 255): [(255, 255, 0), (0, 255, 255)],
(255, 0, 0): [(0, 0, 255), (0, 255, 0), (255, 255, 0), (0, 255, 255)],
(0, 255, 0): [(0, 0, 255), (255, 255, 0), (0, 255, 255)],
(255, 255, 0): [],
(0, 255, 255): [(255, 255, 0)]}
if __name__ == '__main__':
to_delete = []
for key, value in dict(dic).items():
if len(value) == 0:
to_delete.append(key)
del dic[key]
for key in dict(dic):
dic[key] = [item for item in dic[key] if item not in to_delete]
print(dic)
Output:
{
(0, 0, 255): [(0, 255, 255)],
(255, 0, 0): [(0, 0, 255), (0, 255, 0), (0, 255, 255)],
(0, 255, 0): [(0, 0, 255), (0, 255, 255)],
(0, 255, 255): []
}
Upvotes: 2
Reputation: 16856
to_del = [k for k, v in dic.items() if len(v) == 0]
_ = [dic.pop(k) for k in to_del]
_ = [dic[k].remove(d) for k in dic.keys() for d in to_del if d in dic[k]]
print (dic)
Output:
{(0, 0, 255): [(0, 255, 255)],
(255, 0, 0): [(0, 0, 255), (0, 255, 0), (0, 255, 255)],
(0, 255, 0): [(0, 0, 255), (0, 255, 255)],
(0, 255, 255): []}
Upvotes: 0
Reputation: 329
You can do something like this:
list1 = [k for k, v in dic.items() if v == []]
newDict1 = {k: v for k, v in dic.items() if v != []}
newDict2 = {k: v for k, v in newDict1.items() if not any(xs in v for xs in list1)}
Explanation of the code:
Upvotes: 2