Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single line of code to check for a key in a 2D nested inner dictionary

Tags:

python

Is there a single line method to check whether a Python 2d dict has an inner key/value?

Right now i do somethng like this:

if d.has_key(k1):
    if d[k1].has_key(k2): 
        # do something

Is there a better way to do this?

Thanks

like image 323
frazman Avatar asked Jun 26 '12 17:06

frazman


People also ask

How do you check the presence of a key in a dictionary?

Check If Key Exists using has_key() method Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.

How do you check if a value is in a nested dictionary Python?

Use get() and Key to Check if Value Exists in a Dictionary Dictionaries in Python have a built-in function key() , which returns the value of the given key. At the same time, it would return None if it doesn't exist.

How do you navigate a nested dictionary in Python?

To access element of a nested dictionary, we use indexing [] syntax in Python.

How do you check if a dictionary contains a value?

values() to check if a value is in a dictionary. Use dict. values() to get the values of a dictionary. Use the expression value in dictionary_values to return True if the value is in the dictionary and False if otherwise.


2 Answers

if k2 in d.get(k1, {}):
    # do something

The above fragment is nice if you don't care about whether k1 actually exists or not and merely want to know whether k2 exists inside of it if it does exist. As you can see from my code snippet, I prefer the in operator, but you could just as easily say

if d.get(k1, {}).has_key(k2):
    # do something

if you prefer that idiom, but the has_key method has been deprecated in Python 3.x, so you should probably avoid it.

like image 183
Eli Courtwright Avatar answered Sep 23 '22 08:09

Eli Courtwright


You can use in:

if k1 in d and k2 in d[k1]:

The has_key method is deprecated and is removed in Python 3.x.

Related:

  • 'has_key()' or 'in'?
like image 29
Mark Byers Avatar answered Sep 22 '22 08:09

Mark Byers