How to Access Value of a Dictionary in Python

To access the value of a dictionary, you can use different methods in Python. Dictionaries are collections of key-value pairs.

The following examples show how to use these methods in Python to access values in a dictionary.

Using Square Brackets

We can use square brackets to access a value from a dictionary.

Suppose we have the following dictionary:

# Create dictionary
Emp_data = {'Joining_Date': '11/12/2021', 'Emp_Name': 'Anita', 'Past_Exp': 2, 'Department': 'R&D', 'Age': 25}

# Accessing the value using the square bracket
joining_date = Emp_data['Joining_Date']

# Show accessed value
print("Accessed element:", joining_date)

Output: 👇️

Accessed element: 11/12/2021

As the output shows, we access the value of the Joining_Date key using square brackets.

Using get() Function

We can use the get() function to access a value from a dictionary.

Suppose we have the same dictionary as above.

We can use the following code to access the value of the Emp_Name key:

# Accessing the value using get() function
Name = Emp_data.get('Emp_Name')

# Show accessed value
print("Accessed element:", Name)

Output: 👇️

Accessed element: Anita

Here, the output shows the value of the Emp_Name key, which we access using the get() function.

Using items() Function

We can use the items() function along with a for loop to access all keys and values in a dictionary.

Suppose we have the same dictionary as above.

We can use the following code to iterate through key-value pairs:

# Iterating through key-value pairs
for key, value in Emp_data.items():
    print(key, value)

Output: 👇️

Joining_Date 11/12/2021
Emp_Name Anita
Past_Exp 2
Department R&D
Age 25

As the output shows, we access each key and its corresponding value in the dictionary.