Dictionary
- Dictionary is a collection of key values used to store data values.
- It is unordered data structure stored ass key and value pair.
- It is built-in type denoted by dict.
- It is a mutable datatype.
- Dictionary is enclosed by curly braces{}
- Key and value pair are separated by comma.(,)
- The separator colon(:)is used between key and the value.
- The key used to map the value.
- Dictionary cannot have two items with the same key.
Dictionary Methods:
Clear() - It removes all the elements from the dictionary.
Copy() - Returns a copy of the dictionary.
Get() - It returns the values of specified key.
Items() - It returns a list containing a tuple for each key value
pair.
Keys()-Returns a list containing dictionary's of keys.
Pop() - Remove the elements with specified keys.
Popitem() - Remove the last inserted key-value pair.
Update() - Updates the dictionary with specified key-value
pairs.
Values() - Returns a list of all the values.
Create A Dictionary:
curly braces{} can be used to create a dictionary in Python.
Syntax:
# create an empty dictionary
my_dict = {}
Example:
Dictionary program to accessing elements , adding elements and removing elements in python
Program:
# create a dictionary
my_dict = {'apple':
2, 'banana': 1, 'orange': 3}
# accessing elements in the dictionary
print(my_dict['apple']) # output: 2
print(my_dict.get('banana')) # output: 1
print(my_dict.get('grape'))
# output: None
# adding elements to the dictionary
my_dict['grape'] = 4
print(my_dict)
# output: {'apple': 2, 'banana': 1, 'orange': 3, 'grape':
4}
# updating an element in the dictionary
my_dict['orange'] = 5
print(my_dict)
# output: {'apple': 2, 'banana': 1, 'orange': 5, 'grape':
4}
# removing an element from the dictionary
del my_dict['banana']
print(my_dict)
# output: {'apple': 2, 'orange': 5, 'grape': 4}
Output:
2
1
None
{'apple': 2, 'banana': 1, 'orange': 3, 'grape': 4}
{'apple': 2, 'banana': 1, 'orange': 5, 'grape': 4}
{'apple': 2, 'orange': 5, 'grape': 4}
More topic in Python