How do I assign a dictionary value to a variable in Python?


You can assign a dictionary value to a variable in Python using the access operator []. 

example

my_dict = {
   'foo': 42,
   'bar': 12.5
}

new_var = my_dict['foo']
print(new_var)

Output

This will give the output −

42

example

This syntax can also be used to reassign the value associated with this key. 

my_dict = {
   'foo': 42,
   'bar': 12.5
}

my_dict['foo'] = "Hello"
print(my_dict['foo'])

Output

This will give the output −

Hello

Lakshmi Srinivas
Lakshmi Srinivas

Programmer / Analyst / Technician

Updated on: 05-Mar-2020

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements