Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for a key in a defaultdict without updating the dictionary (Python)?

I usually use the following idiom when working with a Python dictionary:

try:
    val = dct[key]
except KeyError:
    print key, " is not valid"

since for large dictionaries, the statement

if key in dct:
    # do something

is not very efficient (so I remember reading, but I've noticed it in practice as well)

Today I was working with a defaultdict and for a moment I forgot that a defaultdict will never give you a KeyError but instead will update the original dictionary.

How can I perform a lookup without updating the defaultdict? I really need to print an error so that the user can reenter the key.

Thank you!

UPDATE: Several posters suggested that my belief that if key in dct: is slow is false. I went back and checked the book in which I had read that is better to use try: except:. It is 2002's Python Cookbook, Recipe 1.4 by Alex Martelli, which can be found also online here: Add an entry to dictionary. Old memories are so unreliable! The recipe doesn't mention "slower" and it's not even using in but has_key. It simply says that try: except: is more Pythonic (at least the book version of the recipe). Thanks for the correction and the answers.

like image 374
Lejlek Avatar asked Jan 28 '12 17:01

Lejlek


People also ask

How do you check if a key is in a dictionary Python?

Check If Key Exists Using has_key() The has_key() method is a built-in method in Python that returns true if the dict contains the given key, and returns false if it isn't.

How do I get the value of a specific key in Python?

Python dictionary get() Method Python dictionary method get() returns a value for the given key. If key is not available then returns default value None.

What is the difference between Defaultdict and dict in Python?

The main difference between defaultdict and dict is that when you try to access or modify a key that's not present in the dictionary, a default value is automatically given to that key . In order to provide this functionality, the Python defaultdict type does two things: It overrides .


1 Answers

How can I perform a lookup without updating the defaultdict?

With key in dct, i.e. explicitly.

If this is really too expensive for you (measure and you'll be sure), there are workarounds for specific situations. E.g., if your default value is 'ham' and in some situations you don't want to store (key, 'ham') in the defaultdict when key is not found, you can do

dct.get(key, 'ham')  # will return dct[key] or 'ham' but never stores anything
like image 141
Fred Foo Avatar answered Sep 27 '22 17:09

Fred Foo