Variable as Dictionary key in Python

Our topic of this tutorial is Variable as dictionary key in Python with easy example.

A Dictionary is an unordered collection of elements.

Moreover, they are mutable and indexed by keys.

Create a Dictionary

dictionary = {                    # dictionary created with curly braces
    "key" : "value" ,
    "student_num" : 1

print (dictionary)

However, After creating this sample dictionary there are two things to consider.

  • Key:  The values in Dictionary are accessed through keys.
  • Value: Value is the information or the data.

After that, here is an example to show how variables can be used as keys.

Certainly, the elements in the dictionary are in form of key: value pair.

The keys in the dictionary should be immutable (which cannot be modified).

Program: Variable as Dictionary key in Python

sample = { }          # creates empty dictionary
v1 = "number"         # v1 stores a string
v2 = (1,2,3)          # v2 stores a tuple
v3 = 20               # v3 stores a number

# using v1 , v2  ,v3  as keys in dictionary

sample[v1] = "Hello"
sample[v2] = [1,2,34,67]
sample[v3] = "roll_no"

print (sample)
print (sample[v1])     # the value in the dictionary is accessed by the key v1 [ v1 = "number" ]
Output :

{20: 'roll_no', 'number': 'Hello', (1, 2, 3): [1, 2, 34, 67]}

Note: as dictionary in Python is an unordered collection that might differ from the original sequence.

sample = { }
v1 = [1,2,3]
sample[v1] = "a list"


Guess the output?

Traceback (most recent call last):
File "", line 3, in <module>
sample[v1] = "a list"
TypeError: unhashable type: 'list'

It clearly shows that a list that is mutable cannot be used as a key.

Concluding the topic, Dictionary is used to collect information that is related to keys such as pin_numbers: names,

and also variables can be used as keys in Dictionary in Python.

You may also read:

Leave a Reply

Your email address will not be published. Required fields are marked *