Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

Deleting multiple key value pairs from dictionary in python

I generated a python dictionary for all the duplicate images in a folder. The python dictonary now contains values in the following format:

{
  "image_1.jpg": ['image_xyz.jpg', 'image_abc.jpg'],
  "image_xyz.jpg": ["image_1.jpg", "image_abc.jpg"],
  "image_abc.jpg": ["image_xyz.jpg","image_1.jpg"],
  "image_2.jpg": ["image_3.jpg"],
  "image_3.jpg": ["image_2.jpg"],
  "image_5.jpg": []
}

Each key, value pair thus appears atleast twice in the list. Empty list for keys are present which have no duplicates. Is there a way to delete all the duplicate key value pairs present? so that the dictionary looks like the following:

{
  "image_1.jpg": ['image_xyz.jpg', 'image_abc.jpg'],
  "image_2.jpg": ["image_3.jpg"],
  "image_5.jpg": []
}

I tried using list to first store all the values from the key value pair and then deleting them from the dictionary but it empties the whole dictionary.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
source = {
  "image_1.jpg": ['image_xyz.jpg', 'image_abc.jpg'],
  "image_xyz.jpg": ["image_1.jpg", "image_abc.jpg"],
  "image_abc.jpg": ["image_xyz.jpg","image_1.jpg"],
  "image_2.jpg": ["image_3.jpg"],
  "image_3.jpg": ["image_2.jpg"],
  "image_5.jpg": []
}

dest = dict()

for k,v in source.items():
    ok = True
    for k1,v1 in dest.items():
        if k in v1: ok = False
    if ok: dest[k] = v

print(dest) # New filtered dict

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...