Python Dictionary
Introduction
In this chapter, we will learn to implement a Python Dictionary.
Python Dictionary
![](https://www.csharp.com/UploadFile/Tutorial/admin/diving-into-python-chapter-1299202072020050358/Images/Dictionery.jpg)
- 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’, \ }
![](https://www.csharp.com/UploadFile/Tutorial/admin/diving-into-python-chapter-1299202072020050358/Images/explanation.jpg)
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'])
![](https://www.csharp.com/UploadFile/Tutorial/admin/diving-into-python-chapter-1299202072020050358/Images/assesing Dictionery.jpg)
Operations | Dictionary
![](https://www.csharp.com/UploadFile/Tutorial/admin/diving-into-python-chapter-1299202072020050358/Images/opration dic.jpg)
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'])
![](https://www.csharp.com/UploadFile/Tutorial/admin/diving-into-python-chapter-1299202072020050358/Images/show new entry.jpg)
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'])
![](https://www.csharp.com/UploadFile/Tutorial/admin/diving-into-python-chapter-1299202072020050358/Images/delition dic.jpg)
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
95
19.8k
9.6m