Python dictionary stores the data in key-value pairs. It is a mutable data type. In the dictionary, each key and value are mapped with each other. Sometimes it is also called a mapping data type. Built-in function dict() is used by programmers to create the dictionary. It belongs to dict Class. Dictionary is enclosed in curly brackets{}. In the python dictionary, keys and values are separated using the colon(:) symbol.
Declaring/Defining Dictionary
Python dictionary is defined using curly brackets. The empty dictionary can be defined by programmers. You can add keys and values later using the syntax.
Syntax
x = {}
x[' key_Name ']= value_Name
Check type of x using type() built-in function.
x = {}
print(type(x))
Output
<class 'dict'>
Store values in dictionary
x = {'Name':'Ram','Class':'Cse'}
print(x)
Output
{'Name': 'Ram', 'Class': 'Cse'}
Nested dictionary
x = {'Name':'Rahul','Class':'Civil','Marks':{'Python':96,'Python':89}}
print(x)
Output:-
{'Name': 'Rahul', 'Class': 'Civil', 'Marks': {'Python': 96, 'Python': 89}}
Accessing Dictionary:-
Programers can access either keys and values together using the items() function. You can also access keys or values alone using keys() and values() function respectively according to their requirements. Any one of the loop statements can be used to access the all values by programmers.
Access all values using values() function
d = {'Name':'Ram','Class':'Cse'}
print(d)
Output
{'Name': 'Ram', 'Class': 'Cse'}
for i in d.values(): # Aceess values
print(i)
Output
'Ram'
'Cse'
Access all keys using keys() function
d = {'Name':'Ram','Class':'Cse'}
print(d)
Output
{'Name': 'Ram', 'Class': 'Cse'}
for i in d.keys(): # Aceess keys
print(i)
Output
'Name'
'Class'
Access all keys and values using items() function
d = {'Name':'Ram','Class':'Cse'}
print(d)
Output
{'Name': 'Ram', 'Class': 'Cse'}
for i in d.items(): # Aceess keys and values
print(i)
Output
('Name', 'Ram')
('Class', 'Cse')
Check Length of dictionary
d = {'Name':'Ram','Class':'Cse'}
print(len(d))
Output
2
Change and add items in dictionary:-
Programmers can easily add new keys and values in python. The values of keys are also alter by programmers easily.
d = {'Name':'Ram','Class':'Cse'}
print(d)
Output
{'Name': 'Ram', 'Class': 'Cse'}
Add key Roll_no and set value 5
d['Roll_no']=5
print(d)
Output
{'Name': 'Ram', 'Class': 'Cse','Roll_no':5}
Change Roll_no from 5 to 7
d['Roll_no']=7
print(d)
Output
{'Name': 'Ram', 'Class': 'Cse', 'Roll_no': 7}
Remove items from the dictionary:-
The pop () function is used to remove items from the dictionary. Programmers need to specify the value of the key that they want to delete.
d = {'Name': 'Ram', 'Class': 'Cse','Roll_no':5}
print(d)
Output
{'Name': 'Ram', 'Class': 'Cse', 'Roll_no': 5}
d.pop('Class')
Output
'Cse'
print(d)
Output
{'Name': 'Ram', 'Roll_no': 7}
Post a Comment
Post a Comment