Dictionary Built-in Methods In Python

Python DICTIONARY definition

A dictionary contains a collection of indices, which are called keys, and a collection of values.

Each key is associated with a single value. The association of a key and a value is called a key-value pair or sometimes an item.

A dictionary is like a list, but more general. In a list, the indices have to be integers; in a dictionary they can be (almost) any type.

In mathematical language, a dictionary represents a mapping from keys to values, so you can also say that each key ―maps to a value.

The function dict creates a new dictionary with no items. Because dict is the name of a built-in function.

The collections of the key-value pairs are enclosed within the curly braces {}


Built-in Dictionary methods

The built-in python dictionary methods along with the description are given below.

SN Method Description
1 dic.clear() The clear() method removes all elements from the set
2 dict.copy() It returns a shallow copy of the dictionary.
3 dict.fromkeys(iterable, value = None, /) Create a new dictionary from the iterable with the values equal to value.
4 dict.get(key, default = "None") It is used to get the value specified for the passed key.
5 dict.has_key(key) It returns true if the dictionary contains the specified key.
6 dict.items() It returns all the key-value pairs as a tuple.
7 dict.keys() It returns all the keys of the dictionary.
8 dict.setdefault(key,default= "None") It is used to set the key to the default value if the key is not specified in the dictionary
9 dict.update(dict2) It updates the dictionary by adding the key-value pair of dict2 to this dictionary.
10 dict.values() It returns all the values of the dictionary.
11 len() The len() function returns the number of items in an object. When the object is a string, the len() function returns the number of characters in the string.
12 popItem() The popitem() method removes the item that was last inserted into the dictionary.
13 pop() The pop() method takes a single argument (index) and removes the item present at that index.
14 count() count() method searches the substring in the given string and returns how many times the substring is present in it.
15 index() The index() method searches an element in the list and returns its index


Accessing the dictionary values

We have discussed previously how the data can be accessed in the list and tuple by using the indexing.

The dictionary value can be accessed by using the keys as the keys are unique in the dictionary.



Output:

 --- Student details ---
 Name : Prayag
 Roll No : 15
 Tutor : AIMTOCODE
 Course : Python
 Fees : 29

In above, example, we are aceessing and printing the each values separately by using their unique key from the dictionary.


Alternative way of Accessing

in Python, it also provides us an alternative way of accessing the value by using the get() method to access the dictionary values.

However, it will give the same result as shown below:



Output:

 Student details allready entered .... 
 {'Name': 'Prayag', 'fee': 0, 'rno': 15, 'tutor': 'AIMTOCODE', 'course': 'Python'}
 
 Enter the details of Student....
 Name: Prayag
 Rno: 15
 tutor: AIMTOCODE
 course:Python
 fee:0
 ---Entered new student's details---
 {'Name': 'Prayag', 'fee': '0', 'rno': 15, 'tutor': 'AIMTOCODE', 'course': 'Python'}	

Creates Dictionary

			
 Dict = {"Name": "Prayag","Age": 21}  
		

In the above dictionary Dict, The keys Name, and Age are the string that is an immutable object.

Example



Output:

 Student Details .... 
 {'Name': 'Prayag', 'Age': 21, 'roll no: ': 15, 'Tutorial': 'AIMTOCODE'}

This output format is also an input format. For example, you can create a new dictionary with four items:


Deleting elements using del keyword

We can also delete the item of the dictionary using del keyword as shown below

Example:



Output:

 ---Student detail---
 {'Name': 'Prayag', 'fee': 0, 'rno': 15, 'tutor': 'AIMTOCODE', 'course': 'Python'}
 Deleting Student Name and Tutor: 
 Modified Student Detail is: 
 {'fee': 0, 'rno': 15, 'course': 'Python'}
 Deleting dictionary: Student
 Now trying to print again  

error we get:

Traceback (most recent call last): File "delete-dictionary.py", line 13, in <module> print(Student) NameError: name 'Student' is not defined

Looping In Dictionary

If you use a dictionary in a for statement, it traverses the keys of the dictionary.

For example, prints each key of the dictionrary:

 Student = {"Name": "Prayag", "Rno": 15, "Tutor":"AIMTOCODE", "Subject": "Python", "Fee":2000}  
 for a in Student:  
     print(a);


Output:

 Name
 Rno
 Tutor
 Subject
 Fee

Example 2 printing all only values of the dictionary

 Student = {"Name": "Prayag", "Rno": 15, "Tutor":"AIMTOCODE", "Subject": "Python", "Fee":2000}  
 for a in Student:  
     print(Student[a]);     


Output:

 Prayag
 15
 AIMTOCODE
 Python
 2000

Example 3: printing items of dictionary using items() method.


 Student = {"Name": "Prayag", "Rno": 15, "Tutor":"AIMTOCODE", "Subject": "Python", "Fee":2000}  
 for a in Student.items():  
     print(a);     


Output:

 ('Name', 'Prayag')
 ('Rno', 15)
 ('Tutor', 'AIMTOCODE')
 ('Subject', 'Python')
 ('Fee', 2000)


Dictionary as a Collection of Counters

Suppose you are given a string and you want to count how many times each letter appears.

There are several ways you could do it:

  • You could create 26 variables, one for each letter of the alphabet. Then you could traverse the string and, for each character, increment the corresponding counter, probably using a chained conditional.
  • You could create a list with 26 elements. Then you could convert each character to a number (using the built-in function ord), use the number as an index into the list, and increment the appropriate counter.
  • You could create a dictionary with characters as keys and counters as the corresponding values. The first time you see a character, you would add an item to the dictionary. After that you would increment the value of an existing item. Each of these options performs the same computation, but each of them implements that computation in a different way.
    • An implementation is a way of performing a computation; some implementations are better than others. For example, an advantage of the dictionary implementation is that we don‘t have to know ahead of time which letters appear in the string and we only have to make room for the letters that do appear.

Here is what the code might look like:

 def histogram(s):
     d = dict()
     for c in s:
         if c not in d:            
             [c] = 1
         else:
             d[c] += 1
     return d

The name of the function is histogram, which is a statistical term for a collection of counters (or frequencies). The first line of the function creates an empty dictionary. The for loop traverses the string. Each time through the loop, if the character c is not in the dictionary, we create a new item with key c and the initial value 1 (since we have seen this letter once). If c is already in the dictionary we increment d[c].

Here‘s how it works:

 >>> h=histogram('python programmimg')
 17
 >>> h
 {'a': 1, ' ': 1, 'g': 2, 'i': 1, 'h': 1, 'm': 3, 'o': 2, 'n': 1, 'p': 2, 'r': 2, 't': 1, 'y': 1}

The histogram indicates that the letters 'a ' and ' ' appear once; 'g' appears twice, and so on. Dictionaries have a method called get that takes a key and a default value. If the key appears in the dictionary, get returns the corresponding value; otherwise it returns the default value.


Example:


Built-in Dictionary functions

The built-in python dictionary methods along with the description are given below.

SN Function Description
1 cmp(dict1, dict2) It compares the items of both the dictionary and returns true if the first dictionary values are greater than the second dictionary, otherwise it returns false.
2 len(dict) It is used to calculate the length of the dictionary.
3 str(dict) It converts the dictionary into the printable string representation.
4 type(variable) It is used to print the type of the passed variable.