How to Make a Dictionary That Returns Key for Keys Missing from the Dictionary Instead of Raising Keyerror

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

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

Why dict.get(key) instead of dict[key]?

It allows you to provide a default value if the key is missing:

dictionary.get("bogus", default_value)

returns default_value (whatever you choose it to be), whereas

dictionary["bogus"]

would raise a KeyError.

If omitted, default_value is None, such that

dictionary.get("bogus")  # <-- No default specified -- defaults to None

returns None just like

dictionary.get("bogus", None)

would.

Handle missing keys in python dictionary

for instance in reservation.get("Instances", []):
private_ip_address = instance.get("PrivateIpAddress" , None)
public_ip_address = instance.get("PublicIpAddress" , None)
if private_ip_address and public_ip_address:
... do stuff...
elif private_ip_address:
...do stuff..
else:
...do stuff..

Try this one

How can I call __missing__ from dict

There is no dict.__missing__; just drop the call to super().__missing__ (and raise a KeyError). The method is optional and has no default implementation.

Alternatively, if you want to support multiple inheritance properly, you could catch the AttributeError exception:

class Foo(dict):
def __missing__(self, key):
print('missing {}'.format(key))
try:
return super().__missing__(key)
except AttributeError:
raise KeyError(key)

How to create if-else statements on dicts with missing keys

Just check if the key is actually in dict.keys()

df = [{'data':'test', 'videos':5, 'likes':4}, {'data':'test','likes':4}]
videos = []
for i in df:
if 'video' in i.keys():
videos.append(i)
else:
videos.append('None')

How to return a value when you have KeyError Python?

There are three main ways.

Let's assume you have the simplified dict:

names = {123: 'Bob Roberts', 456: 'Alice Albertsons'}

And we're going to look up a name with ID 789, and we want to get John Doe when 789 isn't found in the names dictionary.

Method 1: Use the get method, which accepts a default value:

name_789 = names.get(789, 'John Doe')

Method 2: Use the setdefault method, which accepts a default value, and will also add that default as the new value in the dict if needed:

name_789 = names.setdefault(789, 'John Doe')

Method 3: Create the dictionary as a defaultdict instead:

names = collections.defaultdict((lambda: 'John Doe'), [
(123, 'Bob Roberts'), (456, 'Alice Albertsons')
])

name_789 = names[789]

Note: Method 1 (get) is often really useful for nested dictionaries.

For example: outer.get(outer_key, {}).get(middle_key, {}).get(inner_key) will return outer[outer_key][middle_key][inner_key] if possible, or just None if any of the dicts needed are missing.

How can I remove a key from a Python dictionary?

To delete a key regardless of whether it is in the dictionary, use the two-argument form of dict.pop():

my_dict.pop('key', None)

This will return my_dict[key] if key exists in the dictionary, and None otherwise. If the second parameter is not specified (i.e. my_dict.pop('key')) and key does not exist, a KeyError is raised.

To delete a key that is guaranteed to exist, you can also use

del my_dict['key']

This will raise a KeyError if the key is not in the dictionary.

Return a default value if a dictionary key is not available

You can use dict.get()

value = d.get(key)

which will return None if key is not in d. You can also provide a different default value that will be returned instead of None:

value = d.get(key, "empty")

Defaultdict return key as default

As I mentioned in a comment, you can define your own dictionary subclass that does what you want (simply echos missing keys — it doesn't add them):

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

mydict = MyDefaultDict({'A':'a',
'B':'b',
'C':'c'})

print(f"{mydict['D']=}") # -> mydict['D']='D'



Related Topics



Leave a reply



Submit