Get key in dictionary python

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Let’s see how to get the key by value in Python Dictionary. 

    Example: One Liner Code

    Python3

    my_dict ={"Java":100, "Python":112, "C":11}

    print("One line Code Key value: ", list(my_dict.keys())

          [list(my_dict.values()).index(100)])

    Output:

    Java

    Extract Key from Python Dictionary using Value

    Method 1: Get the key by value using list comprehension

    A list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element in the Python list to get the key from a value in Dictionary.

    Python3

    dic ={"geeks": "A","for":"B","geeks":"C"}

    value = {i for i in dic if dic[i]=="B"}

    print("key by value:",value)

    Output:

    key by value: {'for'}

    Method 2: Get the key by value using a list.index()

    The index() method returns the index of the corresponding value in a list. The approach used here is to find two separate lists of keys and values. Then fetch the key using the position of the value in the val_list. As key at any position N in key_list will have a corresponding value at position N in val_list. 
      

    Python3

    my_dict ={"java":100, "python":112, "c":11}

    key_list = list(my_dict.keys())

    val_list = list(my_dict.values())

    position = val_list.index(100)

    print(key_list[position])

    Output: 

    java

    Method 3: Get the key by value using dict.item()

    We can also fetch the key from a value by matching all the values using the dict.item() and then print the corresponding key to the given value. 

    Python3

    def get_key(val):

        for key, value in my_dict.items():

            if val == value:

                return key

        return "key doesn't exist"

    my_dict = {"Java": 100, "Python": 112, "C": 11}

    print(get_key(100))

    print(get_key(11))

    Output: 

    Java
    C

    Given a dictionary, write a Python program to get the dictionary keys as a list. 

    Examples:

    Input  : {1:'a', 2:'b', 3:'c'}
    Output : [1, 2, 3]
    
    Input  : {'A' : 'ant', 'B' : 'ball'}
    Output : ['A', 'B']

    Method 1: Get dictionary keys as a list using dict.keys()

    The dict.keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion.

    Python3

    dict = {1: 'Geeks', 2: 'for', 3: 'geeks'}

    print(dict.keys())

    Output:

    dict_keys([1, 2, 3])

    Method 2: Get dictionary keys as a list using dict.keys()

    Python list() function takes any iterable as a parameter and returns a list. In Python iterable is the object you can iterate over.

    Python3

    mydict = {1: 'Geeks', 2: 'for', 3: 'geeks'}

    keysList = list(mydict.keys())

    print(keysList)

    Output:

    [1, 2, 3]

    Method 3: Get dictionary keys as a list using For Loop and append method

    In this method, we will iterate over each key using the dict.keys() function and append them to a new list named as a list.

    Python3

    def getList(dict):

        list = []

        for key in dict.keys():

            list.append(key)

        return list

    dict = {1:'Geeks', 2:'for', 3:'geeks'}

    print(getList(dict))

    Output:

    [1, 2, 3]

    Method 4:  Dictionary Keys to List using List Comprehension

    Here, we will try to shorten our code using list comprehension in Python.

    Python3

    dict = {1: 'Geeks', 2: 'for', 3: 'geeks'}

    keysList = [key for key in dict]

    print(keysList)

    Output:

    [1, 2, 3]

    Method 5: Dictionary Keys to List using Unpacking with * 

    Unpacking with * works with any object that is iterable and, since dictionaries return their keys when iterated through, you can easily create a list by using it within a list literal. 

    Python3

    def getList(dict):

        return [*dict]

    dict = {'a': 'Geeks', 'b': 'For', 'c': 'geeks'}

    print(getList(dict))

    Output:

    ['a', 'b', 'c']

    Method 6: Dictionary Keys to List using itemgetter

    The itemgetter from the operator module returns a callable object that fetches an item from its operand using the operand’s __getitem__() method. This method is then mapped to dict.items() and then typecasted to list. 

    Python3

    from operator import itemgetter

    def getList(dict):

        return list(map(itemgetter(0), dict.items()))

    dict = {'a': 'Geeks', 'b': 'For', 'c': 'geeks'}

    print(getList(dict))

    Output:

    ['a', 'b', 'c']

    How do you get a specific key from a dictionary Python?

    Method 1 : Using List. Step 1: Convert dictionary keys and values into lists. Step 2: Find the matching index from value list. Step 3: Use the index to find the appropriate key from key list.

    How do I find the dictionary key?

    Method 1: Get dictionary keys as a list using dict. keys().
    Method 2: Get dictionary keys as a list using dict. keys().
    Method 3: Get dictionary keys as a list using For Loop and append method..
    Method 5: Dictionary Keys to List using Unpacking with *.
    Method 6: Dictionary Keys to List using itemgetter..

    Can you get key from value in dictionary Python?

    We can also fetch the key from a value by matching all the values using the dict. item() and then print the corresponding key to the given value.

    How do you get keys in Python?

    The keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion using Python. Parameters: There are no parameters. Returns: A view object is returned that displays all the keys.