Python Dictionary Methods

Various methods are provided to process the elements of a dictionary. These methods generally retrieve or manipulate the contents of a dictionary.


Method Example Description
clear() d.clear() Removes all key-value pairs from dictionary 'd'.
copy() d1.d.copy() Copies all elements from 'd' into a new dictionary 'd1'.
fromkeys() d.fromkeys(s[,v]) Create a new dictionary with keys from sequence 's' and values all set to 'v'.
get() d.get(k[,v]) Returns the value associated with key 'k'.If key is not found,it returns 'v'.
items() d.items() Returns an object that contains key-value pairs of 'd'.The pairs are stored as tuples in the object.
keys() d.keys() Returns a sequence of keys from the dictionary 'd'.
values() d.values() Returns a sequence of values from the dictionary 'd'.
update() d.update(x) Adds all elements from dictionary 'x' to 'd'.
pop() d.pop(k[,v]) Removes the key 'k' and its value from 'd' and returns the value.If key is not found,then the value 'v' is returned.If key is not found and 'v' is not mentioned then 'KeyError' is raised.
setdefault() d.setdefault(k[,v]) If key 'k' is found,its value is returned.If key is not found,then the k,v pair is stored into the dictionary 'd'.

A Python program to retrieve keys, values and key-value pairs from a dictionary.


A Python program to create a dictionary and find the sum of values.


First we create an empty dictionary 'x'. We enter the key into 'k' and value into 'v' and then using the update() method, we will store these key-value pairs into the dictionary 'x', as shown in the following statement:

x.update({k:v})


A Python program to create a dictionary from keyboard and display the elements.


A Python program to create a dictionary with cricket players names and scores in a match. Also we are retrieving runs by entering the player's name.


Using for Loop with Dictionaries

For loop is very convenient to retrieve the elements of a dictionary. Let's take a simple dictionary that contains color code and its name as: