DevOps | Scripts | Automation

Python

How to create and use Python dictionary?

Creating Dictionary:

Dictionary in Python is a Key-Value pair. For example, EmployeeID:1001 is a key-value pair example. To declare empty dictionary we use {} symbol.

Firstdict = {}

Here the Firstdict dictionary is created with no values. Let’s print empty dictrionary.

print(Firstdict)

Output:

Now, we can add values to the dictionary as shown below.

Firstdict = {}
Firstdict['EmpName'] = 'Jack'
Firstdict['EmpId'] = '1000'
print(Firstdict)

Output:

Another way to create a Python dictionary is ,

Firstdict = {'EmpName':'Jack','EmpId':'1000'}

The output remain same as above.

Dictionary also allows you to enter different datatype values. Below created dictionary is with integer and float number.

Firstdict = {'EmpName':'Jack','EmpId':1000,'Ref':2.5}
Accessing Specific Key:

To access the specific value, you need to print that particular key as shown below.

print(Firstdict['EmpName'])

Output:

Deleting Specific key.

To delete the specific key, we need to use del keyword with the specific key that we provide to delete.

del Firstdict['Ref']
print(Firstdict)
Dictionary Methods

To get all the keys for the dictionary, we can use keys() function.

Firstdict = {}
Firstdict = {'EmpName':'Jack','EmpId':1000,'Ref':2.5}
print(Firstdict.keys())
Keys() method Output

To get all values from the dictionary, use the below command.

Firstdict = {}
Firstdict = {'EmpName':'Jack','EmpId':1000,'Ref':2.5}
print(Firstdict.values())
Values() method Output

items() method returns both, keys and values.

items() method Output