Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle undeclared dict key in Python

Tags:

In my Ruby application I have a hash table:

c = {:sample => 1,:another => 2}

I can handle the table like this:

[c[:sample].nil? , c[:another].nil? ,c[:not_in_list].nil?]

I'm trying to do the same thing in Python. I created a new dictionary:

c = {"sample":1, "another":2}

I couldn't handle the nil value exception for:

c["not-in-dictionary"]

I tried this:

c[:not_in_dictionery] is not None

and it is returning an exception instead of False. How do I handle this?

like image 506
shajin Avatar asked Jul 20 '11 00:07

shajin


People also ask

How do you handle a key not in a dictionary Python?

A Python KeyError exception is what is raised when you try to access a key that isn't in a dictionary ( dict ). Python's official documentation says that the KeyError is raised when a mapping key is accessed and isn't found in the mapping. A mapping is a data structure that maps one set of values to another.

What happens if you try to access a dictionary key that doesn't exist?

Notice that when you want to access the value of the key that doesn't exist in the dictionary will result in a KeyError.

What is __ missing __ in Python?

Syntax. The __missing__(self, key) method defines the behavior of a dictionary subclass if you access a non-existent key. More specifically, Python's __getitem__() dictionary method internally calls the __missing__() method if the key doesn't exist.

Why am I getting a KeyError in Python?

Now let us see what a key error is. KeyError in Python is raised when you attempt to access a key that is not in a dictionary. The mapping logic is a data structure that maps one set of data to significant others. Hence, it is an error, which is raised when the mapping is accessed and not found.


1 Answers

In your particular case, you should probably do this instead of comparing with None:

"not_in_dictionary" in c

If you were literally using this code, it will not work:

c[:not_in_dictionary] is not None

Python doesn't have special :keywords for dictionary keys; ordinary strings are used instead.


The ordinary behaviour in Python is to raise an exception when you request a missing key, and let you handle the exception.

d = {"a": 2, "c": 3}

try:
    print d["b"]
except KeyError:
    print "There is no b in our dict!"

If you want to get None if a value is missing you can use the dict's .get method to return a value (None by default) if the key is missing.

print d.get("a") # prints 2
print d.get("b") # prints None
print d.get("b", 0) # prints 0

To just check if a key has a value in a dict, use the in or not in keywords.

print "a" in d # True
print "b" in d # False
print "c" not in d # False
print "d" not in d # True

Python includes a module that allows you to define dictionaries that return a default value instead of an error when used normally: collections.defaultdict. You could use it like this:

import collections

d = collections.defaultdict(lambda: None)
print "b" in d # False
print d["b"] # None
print d["b"] == None # True
print "b" in d # True

Notice the confusing behaviour with in. When you look up a key for the first time, it adds it pointing to the default value, so it's now considered to be in the dict.

like image 165
Jeremy Avatar answered Oct 10 '22 16:10

Jeremy