Python Dictionary
Introduction
In this chapter, we will learn to implement a Python Dictionary.
Python Dictionary

- Values
- Keys
The Keys are for accessing a specific value at an address and the Values are the stuff that is at that address. This might sound a bit confusing but there is no need to worry, one example will smash it all.
- EmpDetails = {‘Mr.X’ : ‘Dev’ , \
- ‘Mr. Y’ : ‘DB Admin’, \
- ‘Mr. Z’ : ‘UI Designer’, \ }

Creating a Dictionary
- EmpDetails = {‘Mr.X’ : ‘Dev’ , \
- ‘Mr. Y’ : ‘DB Admin’, \
- ‘Mr. Z’ : ‘UI Designer’, \ }
- EmpDetails = {‘Mr.X’ : ‘Dev’ , ‘Mr. Y’ : ‘DB Admin’, ‘Mr. Z’ : ‘UI Designer’ };
- dict = {'Programmer': 'Business Layer', 'DataBase Admin': 'Database Layer', 'UI Developer': 'Presentation Layer'};
- print ("dict['Programmer']: ", dict['Programmer'])
- print ("dict['UI Developer']: ", dict['UI Developer'])

Operations | Dictionary

Dictionary | Updating
You can do updates in the dictionary in one of the following ways:
- Adding a new element
- Updating a new key-value
- Modifying an existing entry
- Deleting an existing entry
Let's explore it with an example.
- dict = {'Programmer': 'Business Layer', 'DataBase Admin': 'Database Layer', 'UI Developer': 'Presentation Layer'};
- dict['Programmer'] = 'Architecture Design';
- print ("dict['Programmer']: ", dict['Programmer'])

Dictionary | Deletes
In Python, you either delete a single element or all the dictionary elements. To do delete in a dictionary, we use a del statement.
- dict = {'Programmer': 'Business Layer', 'DataBase Admin': 'Database Layer', 'UI Developer': 'Presentation Layer'};
- del dict['UI Developer'];
- dict.clear(); # remove all entries in dict
- del dict ; # delete entire dictionary
- print ("dict['Programmer']: ", dict['programmer'])
- print ("dict['Database Admin']: ", dict['Database Admin'])

Built-in Tuple functions
Dictionary | Compare
- dict1 = ('CSK', 180)
- dict2 = ('MI', 175)
- print (cmp(dict1, dict2))
- print (cmp(dict2, dict1))
Dictionary | Length
- tup = len ('C# Corner')
- print (a)
Conclusion
In the next chapter, we will learn to Python Exception Handling.
Author
Abhishek Jaiswal
96
19.8k
9.7m