In this example we will show how to use the dictionary in Python. A dictionary is a variable container model that can store any type of object in the format of <key, values> sequence.
Method
- Each key value of the dictionary (key=>value) is split with a colon (:), each pair is separated by a comma (,), and the entire dictionary is enclosed in curly braces ({}) in the following format:
d = {key1 : value1, key2 : value2}
Where the key must be unique, but the value is not necessary to be unique.
- Values can take any data type, but the keys must be immutable, such as strings, numbers, or tuples. The sample code is as follows:
dict = {'City': 'New York', 'Year': '1995', 'Zipcode': '10001'}
Access Element
One can use the key to access the value corresponding to the key.
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
Output:
dict['Name']: John
dict['Age']: 23
Delete
There are three ways to delete data in a dictionary:
- Delete key
- Clear dictionary
- Delete dictionary
Source Code
Based on the description above, a few simple examples are given below to help your understanding on creation, access and deletion of dictionary.
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# !/usr/bin/python3
dict = {'Name': 'John', 'Age': 23, 'Class': 'First'}
print("dict['Name']: ", dict['Name'])
print("dict['Age']: ", dict['Age'])
# Delete Name
del dict['Name']
print('the length of dict after del name is ',len(dict))
# clear the dict
dict.clear()
# printf info
print(str(dict))
Output:
dict['Name']: John
dict['Age']: 23
the length of dict after del name is 2
{}
Tips
- The same key is not allowed to appear twice in dictionary. If the same key is assigned twice when creating dictionary, the latter value will be stored for the key.
- The key must be immutable in dictionary. It can be numbers, strings, or tuples, but lists are not allowed as dictionary keys.