{"id":2606,"date":"2023-10-16T08:30:10","date_gmt":"2023-10-16T03:00:10","guid":{"rendered":"https:\/\/python-programs.com\/?p=2606"},"modified":"2023-11-10T11:42:22","modified_gmt":"2023-11-10T06:12:22","slug":"python-check-if-a-value-exists-in-the-dictionary","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-check-if-a-value-exists-in-the-dictionary\/","title":{"rendered":"Python: Check if a Value Exists in the Dictionary"},"content":{"rendered":"

In this article, we will be discussing how to check if a value exists in the python dictionary or not.<\/p>\n

Before going to the different method to check let take a quick view of python dictionary and some of its basic function that we will be used in different methods.<\/p>\n

Dictionary in python is an unordered collection of elements. Each element consists of key-value pair.It must be noted that keys in dictionary must be unique because if keys will not unique we might get different values in the same keys which is wrong. There is no such restriction in the case of values.<\/p>\n

For example: {“a”:1, “b”:2, “c”:3, “d”,4}<\/p>\n

Here a,b,c, and d are keys, and 1,2,3, and 4 are values.<\/p>\n

Now let take a quick look at some basic method that we are going to use.<\/p>\n

    \n
  1. keys():\u00a0 The keys() method in Python Dictionary, return a list of keys that are present in a particular dictionary.<\/li>\n
  2. values(): The values() method in Python Dictionary, return a list of values that are present in a particular dictionary.<\/li>\n
  3. items(): The items() method in python dictionary return a list of key-value pair.<\/li>\n<\/ol>\n

    syntax for using keys() method: dictionary_name.keys()<\/p>\n

    syntax for using values() method: dictionary_name.values()<\/p>\n

    syntax for using items() method: dictionary_name.items()<\/p>\n

    Let us understand this with basic code<\/p>\n

    d={\"a\":1,\r\n    \"b\":2,\r\n    \"c\":3,\r\n    \"d\":4\r\n    }\r\nprint(type(d))\r\nprint(d.keys())\r\nprint(d.values())\r\nprint(d.items())<\/pre>\n

    Output<\/p>\n

    <class 'dict'>\r\ndict_keys(['a', 'b', 'c', 'd'])\r\ndict_values([1, 2, 3, 4])\r\ndict_items([('a', 1), ('b', 2), ('c', 3), ('d', 4)])<\/pre>\n

    Here we see that d is our dictionary and has a,b,c, and d as keys and 1,2,3,4 as values and items() return a tuple of key-value pair.<\/p>\n

    Different methods to check if a value exists in the dictionary<\/h2>\n