Some Functions of Dictionary


☞ Following are the functions of tuple :

 1. len()
 2. clear()
 3. get()
 4. items()
 5. keys()
 6. values()
 7. copy()
 8. fromkeys()
 9. setdefault()
10. pop()
11. popitem()
12. update()
13. max()
14. min()
15. sorted()

len() :

  • It returns the length of the dictionary.
Syntax :
 
len(<dictionary>)
Example :
 
D = {10:"Ten", 20:"Twenty", 30:"Thirty"}
print (len(D))
Output :
 
3

clear() :

  • It removes all items from the particular dictionary.
Syntax :
 
<dictionary>.clear()
Example :
 
D = {10:"Ten", 20:"Twenty", 30:"Thirty"}
D.clear()
print (D)
Output :
 
{}

get() :

  • It returns a value for the given key.
  • If the key is not available, then it returns None.
Syntax :
 
<dictionary>.get(<key>, default=None)
Example 1 :
 
D = {10:"Ten", 20:"Twenty", 30:"Thirty"}
a = D.get(20)
print (a)
b = D.get(50)     #it will give None
print (b)
Output :
 
Twenty
None
Example 2 :
 
D = {10:"Ten", 20:"Twenty", 30:"Thirty"}
a = D.get(20, "hello")
print (a)
b = D.get(50, "hello")      #it will default value-hello
print (b)
Output :
 
Twenty
hello

items() :

  • It returns a list of tuples having key-value pairs.
Syntax :
 
<dictionary>.items()
Example :
 
D = {10:"Ten", 20:"Twenty", 30:"Thirty"}
print(D.items())
Output :
 
dict_items([(10, 'Ten'), (20, 'Twenty'), (30, 'Thirty')])

keys() :

  • It returns a list of the keys from key-value pairs in a dictionary.
Syntax :
 
<dictionary>.keys()
Example :
 
D = {10:"Ten", 20:"Twenty", 30:"Thirty"}
print(D.keys())
Output :
 
dict_keys([10, 20, 30])

values() :

  • It returns a list of the values from key-value pairs in a dictionary.
Syntax :
 
<dictionary>.values()
Example :
 
D = {10:"Ten", 20:"Twenty", 30:"Thirty"}
print(D.values())
Output :
 
dict_values(['Ten', 'Twenty', 'Thirty'])

copy() :

  • It is used to create a new dictionary and changes made in the base dictionary will not be reflected.
Syntax :
 
<dictionary_new> = <dictionary_old>.copy()
Example :
 
D1= {10:"Ten", 20:"Twenty", 30:"Thirty"}
D2 = D1.copy()
print(D1, id(D1))
print(D2, id(D2))
Output :
 
{10: 'Ten', 20: 'Twenty', 30: 'Thirty'} 2287432443264
{10: 'Ten', 20: 'Twenty', 30: 'Thirty'} 2287394766784
NOTE : If we make changes in D1 are not reflected in D2 because they are stored at different addresses.

☞ If we will use assignment(=) operator, then changes will reflect in both dictionaries.

Syntax :
 
<dictionary_new> = <dictionary_old>
Example :
 
D1= {10:"Ten", 20:"Twenty", 30:"Thirty"}
D2 = D1
print(D1, id(D1))
print(D2, id(D2))
Output :
 
{10: 'Ten', 20: 'Twenty', 30: 'Thirty'} 2215183394176
{10: 'Ten', 20: 'Twenty', 30: 'Thirty'} 2215183394176
NOTE : If we make changes in D1 are also reflected in D2 because they are stored at the same address.

fromkeys() :

  • It is used to create a dictionary from a collection of keys(tuple/list).
Syntax :
 
<dictionary>.fromkeys(<collection_of_keys>, <default_value>)
Example 1 :
 
key = [10, 20, 30]
value = ["A", "B", "C"]
D = dict.fromkeys(key, value)
print(D)
Output :
 
{10: ['A', 'B', 'C'], 20: ['A', 'B', 'C'], 30: ['A', 'B', 'C']}
Example 2 :
 
key = [10, 20, 30]
D = dict.fromkeys(key)
print(D)
Output :
 
{10: None, 20: None, 30: None}

setdefault() :

  • It returns :
    1. Value of the key, if it is in the dictionary.
    2. None, if the key is not in the dictionary and default_value is not specified.
    3. Default_value, if key is not in the dictionary and default_value is specified.
  • If the key does not exist, it inserts the key with the specified value.
Syntax :
 
variable_name = <dictionary>.setdefault(<key>, <default_value>)
Example :
 
D = {"Name" : "Avlokan", "Gender" : "Male"}
print(D)
name = D.setdefault("Name", "Not Available")
dob = D.setdefault("Date", "Not Available")
gender = D.setdefault("gender")
print("Name =",name)
print("Date_of_birth =",dob)
print("Gender = ", gender)
Output :
 
{'Name': 'Avlokan', 'Gender': 'Male'}
Name = Avlokan
Date_of_birth = Not Available
Gender =  None

pop(key) :

  • It is used to delete the item specified by the key from the dictionary.
  • It returns the deleted value.
Syntax :
 
<dictionary>.pop(<key>)
Example :
 
D = {"A" : 10, "B" : 20, "C" : 30}
print("Deleted value =", D.pop("B"))
print(D)
Output :
 
Deleted value = 20
{'A': 10, 'C': 30}
NOTE : pop() without argument will give TypeError: pop expected at least 1 argument, got 0

popitem() :

  • It removes the last item from the dictionary.
  • It returns this deleted item.
Syntax :
 
<dictionary>.popitem()
Example :
 
D = {"A" : 10, "B" : 20, "C" : 30}
print("Deleted item =", D.popitem())
print(D)
Output :
 
Deleted item = ('C', 30)
{'A': 10, 'B': 20}

update() :

  • It is used to merge one dictionary into another dictionary.
  • It overwrites the value of the same key.
Syntax :
 
<dictionary_1>.update(<dictionary_2>)
Example :
 
D1 = { "B" : 10, "C" : 20}
D2 = { "A" : 50, "D" : 30, "B" : 40}
D1.update(D2)
print(D1)
print(D2)
Output :
 
{'B': 40, 'C': 20, 'A': 50, 'D': 30}
{'A': 50, 'D': 30, 'B': 40}

min() :

  • It returns a key having minimum value.
Syntax :
 
min(<dictionary>)                  #will give minimum key
min(<dictionary>.values())         #will give minimum value   
Example :
 
D1 = { "B" : 10, "C" : 20, "A" : 30}
print(min(D1))                   #will give mininum key
print(min(D1.values()))          #will give mininum value

D2 = { 50 : "abc", 30 : "xyz", 40 : "uvw"}
print(min(D2))                   #will give mininum key
print(min(D2.values()))          #will give mininum value
Output :
 
A
10
30
abc
NOTE : min() check for the characters in a string on the basis of their ASCII values. If there are two strings in a dictionary, then the first different character in the strings is checked.

max() :

  • It returns a key having maximum value.
Syntax :
 
max(<dictionary>)                 #will give maximum key
max(<dictionary>.values())        #will give maximum value
Example :
 
D1 = { "B" : 10, "C" : 20, "A" : 30}
print(max(D1))                   #will give maximum key
print(max(D1.values()))          #will give maximum value


D2 = { 50 : "abc", 30 : "xyz", 40 : "uvw"}
print(max(D2))                   #will give maximum key
print(max(D2.values()))          #will give maximum value
Output :
 
C
30
50
xyz
NOTE : max() check for the characters in a string on the basis of their ASCII values. If there are two strings in a dictionary, then the first different character in the strings is checked.

sorted() :

  • It is used to sort the elements of a dictionary by its key or value.
  • It returns the list of key, values or items.
Syntax :
 
sorted( <tuple>)
sorted( <tuple>, reverse = True)
Example :
 
D1 = { "B" : 10, "C" : 20, "A" : 30}
print(sorted(D1))                   #according to key
print(sorted(D1.values()))          #according to value
print(sorted(D1.items()))           #according to key
print("------------------")
print(sorted(D1, reverse=True))                       
print(sorted(D1.values(), reverse=True))
print(sorted(D1.items(), reverse=True))
Output :
 
['A', 'B', 'C']
[10, 20, 30]
[('A', 30), ('B', 10), ('C', 20)]
------------------
['C', 'B', 'A']
[30, 20, 10]
[('C', 20), ('B', 10), ('A', 30)]