Python – Dictionary

In Python, a dictionary is a sort of data container that may hold numerous pieces of information in a single variable. It can include components of many data kinds and contains data in key-value pairs. Because dictionary elements are not ordered, index numbers cannot be used to retrieve dictionary elements. The keys of a dictionary are immutable and so cannot be changed. It also prohibits the use of multiple items with the same key (no duplicate keys).

Create Dictionary

A Python – Dictionary may be made by using a comma to separate the components and surrounding them with curly brackets. It may also be generated with the help of the dict() method.

#Dictionary with multiple datatypes
Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
print(Info)

#Creating dictionary with constructor
Info = dict(name="Marry", age=20, city="Newyork")
print(Info)

The output of the above code will be:

{'name': 'John', 'age': 25, 'city': 'London'}
{'name': 'Marry', 'age': 20, 'city': 'Newyork'}

Access element of a Dictionary

A key encased in square brackets [ can be used to access a dictionary entry. The get() method can also be used to do the same thing.

Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
print(Info["city"])
print(Info.get("name"))

The above code will give the following output:

London
John

Modify values in Dictionary

To change the value, use the key to assign a new value.

Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
Info["city"] = "Paris"
print(Info)

The above code will give the following output:

{'name': 'John', 'age': 25, 'city': 'Paris'}

Dictionary Length

To get the total number of key-value pairs in the dictionary, use the len() function.

Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
print(len(Info))

The output of the above code will be:

3

Loop over Dictionary’s keys

This technique may be used to access the keys of a dictionary one at a time.

Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
for x in Info:
  print(x)

The output of the above code will be:

name
age
city

Loop over Dictionary’s values

This technique may be used to access the values of a dictionary one by one.

Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
#first method
for x in Info:
  print(Info[x])

print()
#second method
for x in Info.values():
  print(x)

Each method yields the same outcome. The following is the result of the above code:

John
25
London

John
25
London

Check a Key in the Dictionary

The in keyword can be used to determine whether or not a given key exists in the dictionary.

Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
if "lastname" in Info:
  print("Yes, 'lastname' is a key in the dictionary.")
else:
  print("No, 'lastname' is not a key in the dictionary.")

The above code will give the following output:

No, 'lastname' is not a key in the dictionary.

Add elements in Dictionary

This may be accomplished by giving new index keys values.

Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
Info["gender"] = "Male"
print(Info)

The output of the above code will be:

{'name': 'John', 'age': 25, 'city': 'London', 'gender': 'Male'}

Delete elements of a Dictionary

There are several methods for removing elements from a dictionary:

  • pop() – deletes specified key and its value in the dictionary.
  • popitem() – deletes last key-value pair of the dictionary. Please note that the dictionary is an unordered data container, hence last key-value pair is not defined.
  • clear() – deletes all key-value pairs of the dictionary.
  • del – deletes a key-value pair of a dictionary. can be used to delete the dictionary itself.

The following example shows how to utilise the dictionary’s pop() and popitem() functions.

Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
Info.pop("city")
print(Info)

Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
Info.popitem()
print(Info)

The above code will give the following output:

{'name': 'John', 'age': 25}
{'age': 25, 'city': 'London'}

The following example shows how to utilise the dictionary’s clear() and del functions.

Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
Info.clear()
print(Info)

Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
del Info["city"]
print(Info)
del Info
print(Info)

The above code will give the following output:

{}
{'name': 'John', 'age': 25}

Traceback (most recent call last):
  File "Main.py", line 17, in <module>
    print(Info)
NameError: name 'Info' is not defined

Copy Dictionary

Either the = operator or the copy() function can be used to make a dictionary copy.

  • = operator: Using dict2 = dict1, a reference of dict1 can be created into dict2. Any change to dict1 will be reflected in dict2 also.
  • copy(): This will create an independent copy of a dictionary.
Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
Info_1 = Info
Info_2 = Info.copy()

# Info_1 dictionary is a reference of Info
print(Info_1) 
# Info_2 dictionary is a copy of Info   
print(Info_2,"\n")     

#deletes city key from the dictionary
Info.pop("city")  

# displaying result after operation
print(Info_1)   
print(Info_2)

The output of the above code will be:

{'name': 'John', 'age': 25, 'city': 'London'}
{'name': 'John', 'age': 25, 'city': 'London'}

{'name': 'John', 'age': 25}
{'name': 'John', 'age': 25, 'city': 'London'}

Also Read: Java – Continue Statement

Leave a Reply

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