# Creating a Dictionary
d = {1: ‘One', 2: ‘Two', 3: ‘Three'}
b={"name" :"ajay","class":"11","rollno":25}
# Creating an empty Dictionary
Dict = {}
# Creating a Dictionary with dict() method
a = dict()
b=dict(d)
#access value of given key
>>> d['name']
'ajay'
>>> d['rollno']
25
>>>d[1]
One
#access value of given key sing get() method
>>> d.get('name')
'ajay’
# change value of given key
>>> d['name']='harshit'
>>> d
{'name': 'harshit', 'class': '11', 'rollno': 25}
Add new item in Dictionary
We can easily add new element in dictionary by the following way
A = {1 : "One", 2 : "Two", 3 : "Three"}
A[4] = "Four"
print(A)
OUTPUT
{1 : "One", 2 : "Two", 3 : "Three", 4 : "Four"}
#update()
appends the key-value pair of the dictionary passed as the argument to the key-value pair of the given dictionary.
>>> dict1 = {'Mohan':95, 'Ram':89,'Suhel':92, 'Sangeeta':85}
>>> dict2 = {'Sohan':79,'Geeta':89}
>>> dict1.update(dict2)
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,'Sangeeta': 85, 'Sohan': 79, 'Geeta':89}
>>> dict2
{'Sohan': 79, 'Geeta': 89}
>>> car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
>>> car.update({"color":"white"})
>>> car
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'white’}
>>> car.update({"color":"blue","type":"petrol"})
>>> car
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'blue', 'type': 'petrol'}
We can also join two dictionaries into one by using update() method. It merge the keys and values of one dictionary into other and overwrites the values of the same key.
A = {1 : "One", 2 : "Two", 3 : "Three"}
B = {1: 'Amit', 2: 'Sunil', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}
A.update(B)
print(A)
OUTPUT
{1: 'Amit', 2: 'Sunil', 3: 'Three', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}
#It over writes the values of same keys and add the values of different keys
Removing an element from a Dictionary
There are two ways by which we can delete the elements of dictionary:
1.By using del statement :
Syntax of using del statement is : del <dictionary-name>[key of element]
B = {1: 'Amit', 2: 'Sunil', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}
del B[2] # It will remove the element of key 2
print(B)
OUTPUT:
{1: 'Amit', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}
B = {1: 'Amit', 2: 'Sunil', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}
del B[3] # It will return an error (KeyError) if the key given is not present in the dictionary
print(B)
OUTPUT:
KeyError
2. By Using pop() function :
This function not only delete the element of required key but also return the deleted value.
B = {1: 'Amit', 2: 'Sunil', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}
a=B.pop(2) #It returns the element of Key - 2
print(a)
print(B)
OUTPUT
Sunil
{1: 'Amit', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}
3 By using popitem() function
The popitem() method removes the item that was last inserted into the dictionary.
The removed item is the return value of the popitem() method, as a tuple, see example below.
d={1: 'one', 2: 'two', 3:'three’}
print(d)# delete top or last item from dictionary d.popitem()
print(d)
output
{1: 'one', 2: 'two', 3: 'three'}
{1: 'one', 2: 'two'}
The clear() method
removes all items from the dictionary.
Syntax: dict.clear()
d={1: 'one', 2: 'two', 3:'three’}
print(d)# remove all items from dictionary
d.clear()print(d)
# traversing in dictionary(only traverse in keys)
>>> for i in d:
print(i)
name
class
rollno
# traverse in dictionary values
>>> for i in d:
print(d[i])
harshit
11
25
Write a program to enter roll number and names of five students and store the data in dictionary.
d = { }
for i in range(5):
rno=int(input("Enter roll number"))
name=input("Enter name of student")
d[rno] = name
print(d)
What is the use of copy() method ?
They copy() method returns a copy (shallow copy) of the dictionary.
original = {1:'one', 2:'two'}
new = original.copy()
print('Orignal: ', original)
print('New: ', new)
What is the use of fromkeys() method ?
fromkeys() method returns a dictionary with the specified keys and the specified value.
Syntax
dict.fromkeys(keys, value)
Parameter Description
keys Required. An iterable specifying the keys of the new dictionary
value Optional. The value for all keys. Default value is None
x = ('key1', 'key2', 'key3')
y = 0
thisdict = dict.fromkeys(x, y)
print(thisdict)
Ouput:
['key1': 0, 'key2': 0, 'key3': 0]
Another example
x = ('key1', 'key2', 'key3')
thisdict = dict.fromkeys(x)
print(thisdict)
Output:
['key1': None, 'key2': None, 'key3': None]
setdefault() method returns the value of the item with the specified key.
If the key does not exist, insert the key, with the specified value
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.setdefault("color", "White")
print(x)
Output
White