Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keyerror 1 in my code

I am writing a function that take dictionary input and return list of keys which have unique values in that dictionary. Consider,

ip = {1: 1, 2: 1, 3: 3}

so output should be [3] as key 3 has unique value which is not present in dict.

Now there is problem in given fuction:

def uniqueValues(aDict):

    dicta = aDict
    dum = 0
    for key in aDict.keys():

        for key1 in aDict.keys():

            if key == key1:
                dum = 0
            else:
                if aDict[key] == aDict[key1]:
                    if key in dicta:
                        dicta.pop(key)
                    if key1 in dicta:
                        dicta.pop(key1)

    listop = dicta.keys()
    print listop
    return listop

I am getting error like:

File "main.py", line 14, in uniqueValues if aDict[key] == aDict[key1]: KeyError: 1

Where i am doing wrong?

like image 682
rajesh padgilwar Avatar asked Nov 19 '15 09:11

rajesh padgilwar


People also ask

How do you fix KeyError?

When working with dictionaries in Python, a KeyError gets raised when you try to access an item that doesn't exist in a Python dictionary. This is simple to fix when you're the one writing/testing the code – you can either check for spelling errors or use a key you know exists in the dictionary.

How do I bypass KeyError?

Avoiding KeyError when accessing Dictionary Key We can avoid KeyError by using get() function to access the key value. If the key is missing, None is returned. We can also specify a default value to return when the key is missing.

How do I get rid of KeyError in Python?

A Python KeyError is raised when you try to access an item in a dictionary that does not exist. You can fix this error by modifying your program to select an item from a dictionary that does exist. Or you can handle this error by checking if a key exists first.

Why am I getting a KeyError in Python?

exception KeyError Raised when a mapping (dictionary) key is not found in the set of existing keys. So, try to print the content of meta_entry and check whether path exists or not.


1 Answers

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}))
like image 76
Emile Avatar answered Oct 23 '22 19:10

Emile