zoukankan      html  css  js  c++  java
  • Python: check if key exists in dictionary (6 Ways)

    Suppose we have a dictionary of string and int i.e.

    # Dictionary of string and int
    word_freq = {
    "Hello": 56,
    "at": 23,
    "test": 43,
    "this": 78
    }

    Now we want to check if key ‘test’ exist in this dictionary or not.

    There are different ways to do this. Let’s discuss them one by one.

    Python: check if key in dictionary using if-in statement

    We can directly use the ‘in operator’ with the dictionary to check if a key exist in dictionary or nor. The expression,

    key in dictionary

    Will evaluate to a boolean value and if key exist in dictionary then it will evaluate to True, otherwise False. Let’s use this to check if key is in dictionary or not. For example,

    # Dictionary of string and int
    word_freq = {
    "Hello": 56,
    "at": 23,
    "test": 43,
    "this": 78
    }
     
    key = 'test'
     
    # python check if key in dict using "in"
    if key in word_freq:
    print(f"Yes, key: '{key}' exists in dictionary")
    else:
    print(f"No, key: '{key}' does not exists in dictionary")

    Output:

    Yes, key: 'test' exists in dictionary

    Here it confirms that the key ‘test’ exist in the dictionary.

    Now let’s test a negative example i.e. check if key ‘sample’ exist in the dictionary or not i.e.

    # Dictionary of string and int
    word_freq = {
    "Hello": 56,
    "at": 23,
    "test": 43,
    "this": 78
    }
     
    key = 'sample'
     
    # python check if key in dict using "in"
    if key in word_freq:
    print(f"Yes, key: '{key}' exists in dictionary")
    else:
    print(f"No, key: '{key}' does not exists in dictionary")

    Output:

    No, key: 'sample' does not exists in dictionary

    Here it confirms that the key ‘sample’ does not exist in the dictionary.

    Python: check if dict has key using get() function

    In python, the dict class provides a method get() that accepts a key and a default value i.e.

    dict.get(key[, default])

    Behavior of this function,

    • If given key exists in the dictionary, then it returns the value associated with this key,
    • If given key does not exists in dictionary, then it returns the passed default value argument.
    • If given key does not exists in dictionary and Default value is also not provided, then it returns None.

    Let’s use get() function to check if given key exists in dictionary or not,

    # Dictionary of string and int
    word_freq = {
    "Hello": 56,
    "at": 23,
    "test": 43,
    "this": 78
    }
     
    key = 'sample'
     
    # check if key exists in dictionary by checking if get() returned None
    if word_freq.get(key) is not None:
    print(f"Yes, key: '{key}' exists in dictionary")
    else:
    print(f"No, key: '{key}' does not exists in dictionary")

    Output:

    No, key: 'sample' does not exists in dictionary

    Here it confirmed that the key ‘sample’ does not exist in the dictionary.

    We passed ‘sample’ argument in the get() function, without any default value. As our dictionary does not contain ant key ‘sample’ and no default value is provided, therefore it returned None.

    If we pass the default value along with the key and if key does not exist in the dictionary, then it returns the default value. For example,

    key = 'sample'
     
    # check if key exists in dictionary by checking if get() returned default value
    if word_freq.get(key, -1) != -1:
    print(f"Yes, key: '{key}' exists in dictionary")
    else:
    print(f"No, key: '{key}' does not exists in dictionary")

    Output:

    No, key: 'sample' does not exists in dictionary

    Here it confirmed that the key ‘sample’ does not exist in the dictionary.

    We passed ‘sample’ argument in the get() function, along with the default value -1. As our dictionary does not contain ant key ‘sample’, so get() function returned the the default value.

    We cannot always be sure with the result of dict.get(), that key exists in dictionary or not . Therefore, we should use dict.get() to check existence of key in dictionary only if we are sure that there cannot be an entry of key with given default value.

    Python: check if key in dict using keys()

    keys() function of the dictionary returns a sequence of all keys in the dictionary. So, we can use ‘in’ keyword with the returned sequence of keys to check if key exist in the dictionary or not. For example,

    word_freq = {
    "Hello": 56,
    "at": 23,
    "test": 43,
    "this": 78
    }
     
    key = 'test'
     
    if key in word_freq.keys():
    print(f"Yes, key: '{key}' exists in dictionary")
    else:
    print(f"No, key: '{key}' does not exists in dictionary")

    Output:

    Yes, key: 'test' exists in dictionary

    Here it confirms that the key ‘test’ exist in the dictionary.

    python check if key in dictionary using try/except

    If we try to access the value of key that does not exist in the dictionary, then it will raise KeyError. This can also be a way to check if exist in dict or not i.e.

    def check_key_exist(test_dict, key):
    try:
    value = test_dict[key]
    return True
    except KeyError:
    return False
     
    # Dictionary of string and int
    word_freq = {
    "Hello": 56,
    "at": 23,
    "test": 43,
    "this": 78
    }
     
    key = 'test'
     
    # check if dictionary has key in python
    if check_key_exist(word_freq, key):
    print(f"Yes, key: '{key}' exists in dictionary")
    else:
    print(f"No, key: '{key}' does not exists in dictionary")

    Output:

    Yes, key: 'test' exists in dictionary

    Here it confirms that the key ‘test’ exist in the dictionary.

    In function check_key_exist(), it access the value of given key. If key does not exist then KeyError occurs, in that case it returns False, otherwise it returns True

    Check if key not in dictionary in python using ‘if not in’ statement

    In all the above example, we checked if key exist in dictionary or not. But if want to check if key doesn’t exist in dictionary then we can directly use ‘not in’ with dictionary i.e.

    word_freq = { "Hello": 56, "at": 23, "test": 43, "this": 78 }
     
    key = 'sample'
     
    # Check if key not in dict python
    if key not in word_freq:
    print(f"No, key: '{key}' does not exists in dictionary")
    else:
    print(f"Yes, key: '{key}' exists in dictionary")

    Output:

    No, key: 'sample' does not exists in dictionary

    Here it confirms that the key ‘test’ exist in the dictionary.

    Check if key exist in dictionary using has_key() function

    dict provides a function has_key() to check if key exist in dictionary or not. But this function is discontinued in python 3. So, below example will run in python 2.7 only i.e.

    if word_freq.has_key('test'):
    print("Yes 'test' key exists in dict")
    else:
    print("No 'test' key does not exists in dict")

    Output:

    Yes, key: 'test' exists in dictionary

    Here it confirms that the key ‘test’ exist in the dictionary.

    The complete example is as follows.

    def check_key_exist(test_dict, key):
    try:
    value = test_dict[key]
    return True
    except KeyError:
    return False
     
     
    def main():
     
    # Dictionary of string and int
    word_freq = {
    "Hello": 56,
    "at": 23,
    "test": 43,
    "this": 78
    }
    print("*** Python: check if key in dictionary using if-in statement***")
     
    key = 'test'
     
    # python check if key in dict using "in"
    if key in word_freq:
    print(f"Yes, key: '{key}' exists in dictionary")
    else:
    print(f"No, key: '{key}' does not exists in dictionary")
     
    key = 'sample'
     
    # python check if key in dict using "in"
    if key in word_freq:
    print(f"Yes, key: '{key}' exists in dictionary")
    else:
    print(f"No, key: '{key}' does not exists in dictionary")
     
    print("*** Python: check if dict has key using get() function ***")
     
    key = 'sample'
     
    # check if key exists in dictionary by checking if get() returned None
    if word_freq.get(key) is not None:
    print(f"Yes, key: '{key}' exists in dictionary")
    else:
    print(f"No, key: '{key}' does not exists in dictionary")
     
    key = 'sample'
     
    # check if key exists in dictionary by checking if get() returned default value
    if word_freq.get(key, -1) != -1:
    print(f"Yes, key: '{key}' exists in dictionary")
    else:
    print(f"No, key: '{key}' does not exists in dictionary")
     
    print('python check if key in dict using keys()')
     
    key = 'test'
     
    if key in word_freq.keys():
    print(f"Yes, key: '{key}' exists in dictionary")
    else:
    print(f"No, key: '{key}' does not exists in dictionary")
     
    print('python check if key in dict using try/except')
     
    print('python check if key in dictionary using try/except')
     
    key = 'test'
     
    # check if dictionary has key in python
    if check_key_exist(word_freq, key):
    print(f"Yes, key: '{key}' exists in dictionary")
    else:
    print(f"No, key: '{key}' does not exists in dictionary")
     
    print('check if key not in dictionary in python using if not in statement')
     
    key = 'sample'
     
    # Check if key not in dict python
    if key not in word_freq:
    print(f"No, key: '{key}' does not exists in dictionary")
    else:
    print(f"Yes, key: '{key}' exists in dictionary")
     
    print('check if key not in dictionary in python using has_keys')
     
    if __name__ == '__main__':
    main()

    Output

    *** Python: check if key in dictionary using if-in statement***
    Yes, key: 'test' exists in dictionary
    No, key: 'sample' does not exists in dictionary
    *** Python: check if dict has key using get() function ***
    No, key: 'sample' does not exists in dictionary
    No, key: 'sample' does not exists in dictionary
    python check if key in dict using keys()
    Yes, key: 'test' exists in dictionary
    python check if key in dict using try/except
    python check if key in dictionary using try/except
    Yes, key: 'test' exists in dictionary
    check if key not in dictionary in python using if not in statement
    No, key: 'sample' does not exists in dictionary
    check if key not in dictionary in python using has_keys
  • 相关阅读:
    浅析WPhone、Android的Back与Home键
    Android音频播放之SoundPool
    Button、ImageButton及ImageView详解
    文本 To 音频
    gravity、layout_gravity及orientation
    项目规范性检测工具Lint
    Android视频播放之VideoView
    ContentProvider数据访问详解
    QQ第三方登录
    Android数据共享
  • 原文地址:https://www.cnblogs.com/a00ium/p/13693459.html
Copyright © 2011-2022 走看看