Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a python dictionary that returns key for keys missing from the dictionary instead of raising KeyError?

I want to create a python dictionary that returns me the key value for the keys are missing from the dictionary.

Usage example:

dic = smart_dict() dic['a'] = 'one a' print(dic['a']) # >>> one a print(dic['b']) # >>> b 
like image 227
sorin Avatar asked Jun 03 '11 15:06

sorin


People also ask

How do you get a value from a dictionary in a way that doesn't raise an exception for missing keys?

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. To just check if a key has a value in a dict , use the in or not in keywords.

What method provides a way to avoid a KeyError message by returning a result when attempting to access keys that may not be present in a dictionary?

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.

What does the get () method return when a key is not found in the dictionary none KeyError dictionary list of keys?

get() method returns a default value if the key is missing. However, if the key is not found when you use dict[key] , KeyError exception is raised.

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.


2 Answers

dicts have a __missing__ hook for this:

class smart_dict(dict):     def __missing__(self, key):         return key 

Could simplify it as (since self is never used):

class smart_dict(dict):     @staticmethod     def __missing__(key):         return key 
like image 152
Jochen Ritzel Avatar answered Sep 18 '22 23:09

Jochen Ritzel


Why don't you just use

dic.get('b', 'b') 

Sure, you can subclass dict as others point out, but I find it handy to remind myself every once in a while that get can have a default value!

If you want to have a go at the defaultdict, try this:

dic = defaultdict() dic.__missing__ = lambda key: key dic['b'] # should set dic['b'] to 'b' and return 'b' 

except... well: AttributeError: ^collections.defaultdict^object attribute '__missing__' is read-only, so you will have to subclass:

from collections import defaultdict class KeyDict(defaultdict):     def __missing__(self, key):         return key  d = KeyDict() print d['b'] #prints 'b' print d.keys() #prints [] 
like image 27
Daren Thomas Avatar answered Sep 20 '22 23:09

Daren Thomas