Cameron Sima
Cameron Sima

Reputation: 5385

KeyError in Python when deleting a key from dictionary, but key exists

I am trying to remove a key from a dictionary using the value from another key. The key exists, it says it exists when I type value in dict.keys(), but I get the keyerror when I try to delete it.

def remove_duplicate_length(choices):
    print choices
    print choices['scheme']
    print type(choices['scheme'])
    print choices['scheme'] in choices.keys()
    print 'AABB' in choices.keys()
    scheme = choices['scheme']
    print type(scheme)
    del choices[scheme]

Prints this:

{'ABAB': '2', 'AABB': '6', 'scheme': 'AABB', 'authors': ['Bukowski']}
AABB
<type 'str'>
True
True
<type 'str'>
None

And gives TypeError: 'NoneType' object has no attribute '__getitem__' when trying to reference the result of the return statement, or keyerror: AABB when trying to directly print the result.

I'm printing the result like this:

@route('/', method='POST')
def getUserChoice():
    user_selection = parse_data(request.body.read())
    print user_selection

Upvotes: 0

Views: 4965

Answers (1)

Mauro Baraldi
Mauro Baraldi

Reputation: 6575

Python dict has a very util method, get. Let's say that your dictionary may have, or not, a key. You can use get to retrieve it's key or something else, then you can check if result satisfy your condition.

>>> mydict = {'name': 'Jhon', 'age': 2}
>>> mydict.get('name')
Jhon
>>> mydict.get('lastname', 'Not found')
Not found

In your method, you can check if key exists, and then, delete it.

...
scheme = choices.get('scheme', None)
print type(scheme)
if scheme:
    del choices[scheme]

Upvotes: 1

Related Questions