keyerror 1 in my code

Your main problem is this line:

dicta = aDict

You think you’re making a copy of the dictionary, but actually you still have just one dictionary, so operations on dicta also change aDict (and so, you remove values from adict, they also get removed from aDict, and so you get your KeyError).

One solution would be

dicta = aDict.copy()

(You should also give your variables clearer names to make it more obvious to yourself what you’re doing)

(edit) Also, an easier way of doing what you’re doing:

def iter_unique_keys(d):
    values = list(d.values())
    for key, value in d.iteritems():
        if values.count(value) == 1:
            yield key

print list(iter_unique_keys({1: 1, 2: 1, 3: 3}))

Leave a Comment