Python Programming – Dictionary Functions and Methods

You can learn about Dictionaries in Python Programs with Outputs helped you to understand the language better.

Python Programming – Dictionary Functions and Methods

Just like the other built-in types, dictionaries also have methods and functions.

dict ( )

The dict ( ) constructor builds dictionaries directly from lists of key:value pairs stored as tuples. When the pairs form a pattern, list comprehensions can compactly specify the key:value list.
>>> diet([(‘Amit’, 4139), (‘Ramesh’, 4127), (‘John’, 4098)])
{‘Amit’: 4139, ‘John’: 4098, ‘Ramesh’: 4127}
Since dict ( ) is the name of a built-in function, you should avoid using it as a variable name. You can create a dictionary during run time using dict ( ), also called dynamic allocation.

cmp ( )

cmp ( ) is not supported by Python 3; however, if you are using Python 2 then, cmp ( ) is used to check whether the given dictionaries are same or not. If both are same, it will return 0, otherwise it will return 1 or -1. If the first dictionary has more number of items, than the second one it will return 1, otherwise return -1. For example,
>>> D1 = {‘Sun’: 1, ‘Mon’: 2, ‘Tue’: 3, ‘Wed’: 4, ‘Thurs’: 5, ‘Fri’: 6, ‘Sat’: 7 }
>>> D2 = {‘Sun’: 1, ‘Mon’: 2, ‘Tue’: 3, ‘Wed’: 4, ‘Thurs’: 5, ‘Fri’: 6, ‘Sat’: 7 }
>>> D3 = {‘Sun’: 1, ‘Mon’: 2, ‘Tue’: 3, ‘Wed’: 4, ‘Thurs’: 5 }
>>> cmp ( D1 , D3 ) #Eboth are not equal
1
>>> cmp ( D1 , D2 ) #both are equal
0
>>> cmp ( D3 , D1 )
-1

  • In Python 2, cmp ( ) is used to check whether the given dictionaries are the same or not. cmp ( ) is not supported by Python 3.

len ( )

The len ( ) built-in function gives us the number of items in a dictionary, i.e., it returns the number of key:value pairs. For example,
>>> temps = {‘Delhi’: 20.2, ‘Allahabad’: 15.4, ‘Goa’: 10.5}
>>> len(temps)
3

Let’s Try

>>> week = {‘Mon’ : 1, ‘Tues’:2, ‘Wed’ : 3, ‘Thurs’ :4, ‘Fri’ :5, ‘Sat’ :6, ‘Sun’ :7}
>>> len(week)

clear ( )

The clear ( ) method removes all items from the dictionary. For example,
>>> d = { }
>>> d[‘name’] = ‘Vivek’
>>> d[‘age’] = 18
>>> d
{‘age’: 18, ‘name’: ‘Vivek’}
>>> returned_value = d.clear ( )
>>> d
{ }
>>> print(returned_value)
None

  • The dict. the clear ( ) method is used to remove all elements of dictionary diet and the dict. copy ( ) method is used to return a shallow copy of dictionary diet.

get ( )

The get ( ) method is an easy way to get a value from a dictionary. Ordinarily, when you try to access an item that is not present in the dictionary, things go very wrong. For example,
>>> d = { }
>>> print(d[‘name’])
Traceback (most recent call last):
File “<pyshell#2>”, line 1, in <module> print(d[‘name’])
KeyError: ‘name’
But, when you use get ( ) function, it displays None:
>>> print(d.get(‘name’))
None
As you can see, when you use get() to access a non-existent key, there is no exception. Instead, you get the value None. You may supply your own “default” value, which is then used instead of None. For example,
>>> d.get(‘name’, ‘N/A’)
‘N/A’

pop ( )

The pop ( ) method first gives the value correspond-ing to the given key, and then removes the key:value pair from the dictionary. For example,:
>>> d = {‘x’: 1, ‘y’: 2}
>>> d.pop(‘x’)
1
>>> d
{‘y’: 2}

popitem ( )

The popitem ( ) method is similar to list.pop ( ) method, which pops off the last element of a list. Unlike list.pop ( ), popitem ( ) pops off an arbitrary item because dictionaries do not have the “last element” or any order whatsoever. This may be very useful if you want to remove and process the items one-by-one in an efficient way (without retrieving a list of the keys first). For example,
d1={‘publisher’: ‘BPB’, ‘price’: 99, ‘title’: ‘Computer Science’}
>>> d1.popitem ( )
(‘publisher’, ‘BPB’)
>>> d1
{‘title’: ‘Computer Science’, ‘price’: 99}
>>>
Although pop item ( ) is similar to the list method pop(), there is no dictionary equivalent of append (which adds an element to the end of a list). Since dictionaries have no order, such a method would not make any sense.

keys ( )

The keys and values can be extracted as lists from a dictionary. The keys ( ) method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order. For example,
>>> temps = {‘Delhi’: 20.2, ‘Allahabad’: 15.4, ‘Goa’: 10.5}
>>> temps.keys ( )
dict_keys([‘Goa’, ‘Allahabad’, ‘Delhi’])

Let’s Try

>>> month = {‘Jan’: 1, ‘Feb’: 2, ‘Mar’: 3, ‘Apr’: 4, ‘May’: 5, ‘June’: 6}
>>> month.keys ( )

values ( )

The values ( ) method returns list of values.
>>> temps = {‘Delhi’: 20.2, ‘Allahabad’: 15.4, ‘Goa’: 10.5}
>>> temps.values ( )
dict_values([10.5, 15.4, 20.2])

Let’s Try

>>> month = {‘Jan’: 1, ‘Feb’: 2, ‘Mar’: 3, ‘Apr’: 4, ‘May’: 5, ‘June’.: 6}
>>> month.values ( )

items ( )

It returns a list of tuples (key,value) representing the key:value pairs. It is useful when you wish to iterate through the keys or values of a dictionary, even though in no particular order.
>>> temps = {‘Delhi’: 20.2, ‘Allahabad’: 15.4, ‘Goa’: 10.5}
>>> temps.items ( )
dict_items([(‘Allahabad’, 15.4),
(‘Delhi’, 20.2), (‘Goa’, 10.5)])

Example
Program that converts dictionary into list of tuples.

# convert dictionary to list of tuples
vegetables = { ” carrot ” : 1 , ” peas ” : 2 , ” onion ” : 4 }
items = list ( vegetables . items ( ) )
for item in items:
print ( len ( item ) , item )RUN
>>>
2 ( ‘ carrot ‘ , 1 )
2 ( ‘ peas ” , 2 )
2 ( ‘ onion ‘ , 4 )
>>>

Leave a Reply

Your email address will not be published. Required fields are marked *