Dictionary in Python Examples-DecodingDevOps

A Dictionary is a data structure in python which contains an unordered collection of the items and stores the values like a map. A dictionary does not have any duplicate members and it is indexed Dictionary contains key-value pairs, unlike other data types. keys don't allow to perform the task in many ways that is the keys don't allow the polymorphism. Dictionary keys are case sensitive and it is similar to a real-life dictionary with distinct key-value pairs. Dictionary is accessed using the keys and the dictionary is mutable which means it can be modified and changed. let's see how to create a dictionary and operate on a dictionary

# Dictionary syntax
Dictionary = {'key1':'value1','key2':'value2'}

# creating an empty dictionary
dictionary = { }

# Dictionary with the integer keys
dictionary = {1: 'red', 2: 'blue'}

# Dictionary with the mixed keys
dictionary = {'name': 'ravi', 1: [2, 4, 3]}

# using the inbuilt dict{} function
dictionary = dict({1:'red', 2:'blue'})

We can access the elements from the dictionary using the key enclosed in the square brackets or get method.

Dictionary = { 'name':'hari', 'age': 26}
print(dictionary['age'])
print(dictionary.get['name'])

OUTPUT:
hari
26

Dictionary is mutable. We can add new items or change the value of existing items using the assignment operator. If the key is already present, the value gets updated, else a new key: value pair is added to the dictionary.

# Adding elements to a dictionary

Dictionary = {'name':'ravi', 'age': 26}

Dictionary['name'] = 'hari'
print(Dictionary)
OUTPUT:
'name':'hari', 'age': 26

We can remove a particular item in a dictionary by using the method pop(). This method removes as an item with the provided key and returns the value. The method popitem() can be used to remove and return an arbitrary item (key, value) form the dictionary. All the items can be removed at once using the clear() method. We can also use the del keyword to remove individual items or the entire dictionary itself.

dictionary = {1:3, 2:4, 5:6, 7:8}
print(dictionary.pop(2))
print(dictionary.popitem())
print(dictionary.clear())
print(del dictionary(1)

OUTPUT:
1. {1:3, 5:6, 7:8}

2. {2:4, 5:6, 7:8}

3. {}

4. {2:4, 5:6, 7:8}

Leave a Reply

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