Syntax error Keys associated with Values in Dictionary in Python

Keys associated with Values in Dictionary in Python



When it is required to find the keys associated with specific values in a dictionary, the ‘index’ method can be used.

Below is the demonstration of the same −

Example

 Live Demo

my_dict ={"Hi":100, "there":121, "Mark":189}
print("The dictionary is :")
print(my_dict)

dict_key = list(my_dict.keys())
print("The keys in the dictionary are :")
print(dict_key)
dict_val = list(my_dict.values())
print("The values in the dictionary are :")
print(dict_val)

my_position = dict_val.index(100)
print("The value at position 100 is : ")
print(dict_key[my_position])

my_position = dict_val.index(189)
print("The value at position 189 is")
print(dict_key[my_position])

Output

The dictionary is :
{'Hi': 100, 'there': 121, 'Mark': 189}
The keys in the dictionary are :
['Hi', 'there', 'Mark']
The values in the dictionary are :
[100, 121, 189]
The value at position 100 is :
Hi
The value at position 189 is
Mark

Explanation

  • A dictionary is defined, and is displayed on the console.

  • The keys of the dictionary are accessed using the ‘.keys’ and is converted into a list.

  • This is assigned to a variable

  • The values of the dictionary are accessed using the ‘.values’ and is converted into a list.

  • This is assigned to another variable.

  • The values index is accessed and assigned to a variable.

  • This is displayed as the output.

Updated on: 2021-04-17T12:48:00+05:30

428 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements