1. What are dictionaries in Python
Dictionary is one of the data types which is used to store data in the pairs of key : data.
It is ordered.
It is mutable.
Keys should not be duplicated but data can be same.
Dictionaries are written with curly brackets.
2. Creating a Dictionary
- It is encloses in curly {} braces.
- Separated by a comma (,).
- It holds values in pairs of keys corresponding with data.
- Keys cannot be repeated and are immutable.
- Data can be of any Datatype.
2.1 Example
dict = {1: 'A', 2: 'B', 3: 'C'}
print(dict)
OUTPUT
{1: 'A', 2: 'B', 3: 'C'}
3. Accessing data of a dictionary
We can access the data by their respective keys.
3.1 Syntax
dict = {1: 'A', 2: 'B', 3: 'C'}
print(dict[1])
OUTPUT
A
4. Adding elements to a dictionary
Syntax:
dict = {1: 'A', 2: 'B', 3: 'C'}
print("old dictionary")
print(dict)
new_dict=dict[4]='a'
print("Updated dictionary")
print(dict)
OUTPUT:
old dictionary
{1: 'A', 2: 'B', 3: 'C'}
Updated dictionary
{1: 'A', 2: 'B', 3: 'C', 4: 'a'}
Top comments (0)