Dictionary in Python
Dictionary
It is an unordered sequence/collection of items where each item is a key-value
pair.
Creating a dictionary
A dictionary is created by placing items, (i.e. key-value pair) inside curly braces.
Each key and value is separated by a colon and items separated by comma.
<dictionary_name>={key1: value1, key2:value2,………….., keyN:valueN}
Eg: student={1:’Aman’, 2: ‘Anandhu’, 3: ‘Aravind’}
Here 1:’Aman’ is the first item in dictionary student. There are three items.
1, 2, 3 are the keys and Aman, Anandhu, Aravind are the values.
Empty dictionary
Eg: d={}
Or
Using dict() as
D= dict()
To create a dictionary
Eg: To create a dictionary of students with rollno and name
Student={1:”Aman”,2:”Arjun”,3:”Amit”}
print(Student)
Or
Student={ }
Student[1]=”Aman”
Student[2]=”Arjun”
Student[3]=”Amit”
print(Student)
Accessing elements in a dictionary
To display the value of each item give the statement as,
print(Dictionary_name[key])
Eg: print(Student[1]) O/P: Aman
Traversing a dictionary
Student={1:”Aman”,2:”Arjun”,3:”Amit”}
for i in Student:
print(i, “:”, Student[i])
Append values in dictionary
student={1:”Aman”,2:”Arjun”,3:”Amit”}
student[4]=”Arav”
print(student) O/P: {1:”Aman”,2:”Arjun”,3:”Amit”, 4:”Arav”}
Update the elements
student[2]=”Alok”
print(student) O/P: {1:”Aman”,2:”Alok”,3:”Amit”, 4:”Arav”}
in AND not in operators in dictionary
Checks whether a particular key is in the dictionary or not.
student={1:”Aman”,2:”Arjun”,3:”Amit”}
1 in student O/P: True
2 not in student O/P: False
Dictionary Functions
1) Merge two dictionaries using update()
Two dictionaries can be merged into one by using update(). It merges the keys
and the values of one dictionary with another and overwrites the values of the
same key.
Syntax: dict_name1.update(dict_name2)
Eg 1: D1={1:10,2:20,3:30}
D2={4:40,5:50}
D1.update(D2)
print(D1) O/P: {1:10,2:20,3:30, 4:40,5:50 }
print(D2) O/P: {4:40,5:50 }
Eg 2: D1={1:10,2:20,3:30}
D2={2:30,4:40}
D1.update(D2)
print(D1) O/P: {1:10,2:30,3:30, 4:40}
print(D2) O/P: {2:30,4:40}
2) items()
Returns the content as a list of tuples having key-value pair
D1={1:10,2:20,3:30}
D1.items()
O/P dict_items([(1, 10), (2, 20), (3, 30)])
3) keys()
It returns a list of the key values in the dictionary
D1={1:10,2:20,3:30}
D1.keys()
O/P dict_keys([1, 2, 3])
4) values()
It returns a list of values from key-value pairs in a dictionary.
D1={1:10,2:20,3:30}
D1.values()
O/P dict_values([10, 20, 30])
5) len
It returns the number of items in the dictionary
Syntax: len(d)
6) fromkeys()
This function is used to create dictionary from a collection of keys (tuple/list).
The fromkeys()method returns a new dictionary with the given sequence of
elements as the keys of the dictionary.
Syntax
Dict_name= dict.fromkeys(keys, value)
Value is optional. If value is provided all the items will have the same value. If
not specified, value is set as None
Eg: seq=(1,2,3)
D1=dict.fromkeys(seq)
O/P: D1 ={1:None,2:None,3:None}
D1=dict.fromkeys(seq,20)
O/P: D1 ={1:20,2:20,3:20}
7) copy()
copy() method returns a shallow copy of the dictionary. Copy()method doesn't
take any parameters. It doesn't modify the original dictionary.
Difference in Using copy() method, and = Operator to Copy Dictionaries
When copy() method is used, a new dictionary is created which is filled with a
copy of the references from the original dictionary.
When = operator is used, a new reference to the original dictionary is created.
original = {1:'one', 2:'two'}
new = original
new.clear()
print('new: ', new)
print('original: ', original)
O/P: new: {}
original: {}
****************************************
original = {1:'one', 2:'two'}
new = original.copy()
new.clear()
print('new: ', new)
print('original: ', original)
O/P
new: {}
original: {1: 'one', 2: 'two'}
8) setdefault()
This method returns the value of the item with the specified key. If the key
does not exist, it inserts the key with the specified value.
Syntax: var_name=dict_name.setdefault(key, default_value)
Eg: D1={1:10,2:20,3:30}
X= D1.setdefault(1,”hello”)
print(X) O/P: 10
X= D1.setdefault(4,”hello”)
print(X) O/P: hello
print(D1) O/P: {1:10,2:20,3:30,4:”hello”}
D1.setdefault(5)
print(D1) O/P: {1:10,2:20,3:30,4:”hello”,5:None}
9) min()
This function returns the lowest key in the dictionary.
D1={1:10,2:20,3:30}
min(D1) O/P: 1
• min(D1.values()) O/P: 10
Returns the lowest value in the dictionary.
• min(D1.items()) O/P: (1:10)
Returns the lowest key with its value from the dictionary.
10) max()
This function returns the highest key in the dictionary.
D1={1:10,2:20,3:30}
max(D1) O/P: 3
• max(D1.values()) O/P: 30
Returns the highest value in the dictionary.
• min(D1.items()) O/P: (3:30)
Returns the highest key with its value from the dictionary.
11) sorted()
This method sorts the element of a dictionary by its key or value.
Syntax: sorted(dict_name)
Eg: d3={2:30,1:20,3:10} O/P: [1, 2, 3]
sorted(d3.values()) O/P: [10, 20, 30]
sorted(d3.items()) O/P: [(1, 20), (2, 30), (3, 10)]
To sort in descending order
sorted(d3.items(),reverse=True) O/P:[(3, 10), (2, 30), (1, 20)]
12) get()
get() method returns a value for the given key. If key not available, then
returns default value None.
Syntax: dict_name.get(key,default=None)
Key- this is the key to be searched.
Default – value to be returned in case the key doesn’t exist. Or else returns
None.
Eg: d3={2:30,1:20,3:10}
d3.get(1) O/P: 20
print(d3.get(4)) O/P: None
d3.get(4,"No key exist") O/P: 'No key exist'
d3.get(1,"Never") O/P: 20
Removing an item from a dictionary
To remove an item from dictionary use del or pop() method
1) del statement
Syntax: del dict_name[key]
Eg : D1={1:10,2:20,3:30}
del D1[2]
del statement is used to delete a dictionary completely using a statement
del d1
If the key mentioned in del isn’t in the dictionary, it results in error.
2) pop()
This method will delete an item from the dictionary and also return the
deleted value.
D1.pop(3) O/P: 30
If the key mentioned in pop() isn’t in the dictionary, it results in error.
3) popitem()
This method removes the last item from dictionary and returns the deleted
item.
D1={1:10,2:20,3:30}
D1.popitem() O/P: (3:30)
4) clear()
It removes all items from the dictionary
Syntax: d.clear()
D1={1:10,2:20,3:30}
D1.clear()
print(D1) O/P: {}