Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 list(dictionary.keys()) raises error. What am I doing wrong?

Dictionary:

error['extras'] = {'expiration_month': 'Invalid field [expiration_month] - Missing field "expiration_month"'}

Code:

list(error['extras'].keys())

Result:

*** Error in argument: "(error['extras'].keys())"

If its relevant, I'm running this code in a django process that's paused by pdb.set_trace().

like image 823
user220419 Avatar asked Apr 14 '14 00:04

user220419


People also ask

How do you fix key errors in Python?

The Usual Solution: . If the KeyError is raised from a failed dictionary key lookup in your own code, you can use . get() to return either the value found at the specified key or a default value.

How do you avoid key errors in Python?

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.

Why we get KeyError in Python?

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 fix error 0 in Python?

The Python "KeyError: 0" exception is caused when we try to access a 0 key in a a dictionary that doesn't contain the key. To solve the error, set the key in the dictionary before trying to access it or conditionally set it if it doesn't exist.


1 Answers

I believe the problem is that list is a pdb debugger command. The documentation states the following:

Commands that the debugger doesn’t recognize are assumed to be Python statements and are executed in the context of the program being debugged. Python statements can also be prefixed with an exclamation point (!).

So you could try to prefix list like so:

!list(error['extras'].keys())
like image 85
Justin O Barber Avatar answered Sep 30 '22 00:09

Justin O Barber