Introduction to Dictionary in Python

Dictionary is one of the advanced datatypes in Python which help us tackle lists’ limitations. A list is known as a sequence datatype, while Dictionaries are mapping datatypes.

Let me tell you one story first! A guy named “Weird” was living in a country that had a population of 100 people. Their SSN or Government Id Number is like a count of the population in the country, which means the first person has ID №1, the 10th person’s ID number is 10, and the hundredth is ID №100. The problem that nationals of this country face is their ID gets changed when someone dies! Weird, right? So our hero “Weird”’s Father died, and his ID was changed from 76 to 75.

This is the worst system, right?

See the Nationals list/sequence.

National = ["John Green", "Aristotle", "Plato"......., "Weird",....]

When someone deletes/dies from this list, their index changes. So if we had to access our hero’s ID, we checked the 75th Index, and now, because of his father’s death, his index is 74th. This is one of the major problems of List datatype.

There is another major problem!

See this list:

List = [20, 50, 10, 52, 45, 55]

Can you tell me what these numbers mean? Nobody can! The reason is there is no context to these values. Dictionaries add context to each value.

Dictionary in Python is an unordered collection of data values used to store data like a map; unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. The key value is provided in the dictionary to make it more optimized.

Creating a Dictionary In Python

A Dictionary can be created by placing a sequence of elements within curly {} braces, separated by ‘comma.’ Dictionary holds a pair of values, one being the Key and the other corresponding pair element being its Key: value. Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable.

Note — Dictionaries should have unique keys.

Note — Dictionary keys are case sensitive, the same name, but different cases of Key will be treated distinctly.

Dict = {
"Key1": "value1",
"Key2": "value2"
}

 

We can’t have the same key names. Keys are supposed to be unique. Let’s create another dictionary.

Dict = {
    "Key1": "value1",
    "key1": "value2"
}

print(Dict)

"""
output:

{'Key1': 'value1', 'key1': 'value2'}

"""

If we keep the same key name for two or more keys: value pair. It will only keep the latest value. See the following example.

Dict = {
    "Key1": "value1",
    "Key1": "value2"
}

print(Dict)

"""
output:

{'Key1': 'value2'}

"""

List Vs. Dictionaries

Let’s create two Lists and two dictionaries with the same values.

List = [0, 1, 2, 3, 4, 5]
List1 = [0, 4, 1, 3, 5, 2]

Dict = {"0" : 0, 
        "1" : 1, 
        "2" : 2, 
        "3" : 3, 
        "4" : 4, 
        "5" : 5}

Dict1 = {"0" : 0, "4" : 4, "1" : 1, "3" : 3, "5" : 5, "2" : 2}

print(List[1])
print(List1[1])


print(Dict["1"])
print(Dict1["1"])

"""
output:

1
4
1
1

"""

Notice that each key is separated from its value by a colon (:), each key-value pair is separated by a comma (,), and the entire dictionary is enclosed in curly braces. { }.

# Creating a Dictionary 
# with Integer Keys
Dict_1 = {1: 'hey', 2: 'hello', 3: 'hi', 3: "Namaste"}
print("\nDictionary with the use of Integer Keys: ")
print(Dict_1)
print(Dict_1[1])
  
# Creating a Dictionary 
# with Mixed keys
Dict_2 = {'Name': 'Paul', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict_2)
print(Dict_2[1])

"""
output:

Dictionary with the use of Integer Keys: 
{1: 'hey', 2: 'hello', 3: 'Namaste'}
hey

Dictionary with the use of Mixed Keys: 
{'Name': 'Paul', 1: [1, 2, 3, 4]}
[1, 2, 3, 4]

"""

Dictionary can also be created by the built-in function dict(). An empty dictionary can be created by just placing curly braces{}.

# Creating an empty Dictionary
Dict_1 = {}
print("Empty Dictionary: ")
print(Dict_1)
Dict_1[1] = 'hey'
Dict_1["2"] = 'hello'
Dict_1[3.0] = 'hi'
print("Dictionary: ")
print(Dict_1)
  
# Creating a Dictionary
# with dict() method
Dict_2 = dict({1: 'hey', 2: 'hello', 3:'hi'})
print("\nDictionary with the use of dict(): ")
print(Dict_2)
  
# Creating a Dictionary
# with each item as a Pair
Dict_3 = dict([(1, 'hello'), (2, 'hi')])
print("\nDictionary with each item as a pair: ")
print(Dict_3)

"""
output:

Empty Dictionary: 
{}
Dictionary: 
{1: 'hey', '2': 'hello', 3.0: 'hi'}

Dictionary with the use of dict(): 
{1: 'hey', 2: 'hello', 3: 'hi'}

Dictionary with each item as a pair: 
{1: 'hello', 2: 'hi'}

"""

Dictionaries are one of the widely used datatypes. We have also seen the limitations of lists and understood how dictionaries are one of the important alternatives to tackle those.

In the blog, we have covered the creating a dictionary part. We have also seen the comparison of List and Dictionary Datatype. Now we know why the world requires Dictionary datatype.

Further, we are going to learn the operations and methods of dictionary datatype. For a beginner, it is highly recommended to master creating the dictionary by creating many nested dictionaries. This is required as the first step because many people face confusion, mainly for comma, which acts as a separator between two key: value pairs.