Dictionary Methods in Python (update(), has_key(), fromkeys()


Dictionary in python is one of the most frequently used collection data type. It is represented by hey value pairs. Keys are indexed but values may not be. There are many python-built in functions that make using the dictionary very easy in various python programs. In this topic we will see the three in-built methods namely update(), has_key() and fromkeys().

update()

The method update adds new items to a given dictionary by merging the items from the secondary with first.

Syntax

dict1.update(dict2)
Where dict1 and dict2 are the two input dictionaries.

In the below example we see pairs of dictionaries. The second dictionary gets added to the items in the first dictionary. But the name of keys should be different in the second dictionary to see the effect of merging.

Example

 Live Demo

dict1 = {'Place': 'Delhi', 'distance': 137};
dict2 = {'Temp': 41 };
dict1.update(dict2)
print(dict1)

Running the above code gives us the following result −

{'Place': 'Delhi', 'distance': 137, 'Temp': 41}

has_key()

This method verifies of a key is present in a dictionary or not. This is python2 only feature. This method is not available in python3.

Syntax

dict.has_key(key)

In the below example we check for the presence of some keys in the given dictionaries.

Example

 Live Demo

dict1 = {'Place': 'Delhi', 'distance': 137};
dict2 = {'Temp': 41 };
print(dict1.has_key('Place'))
print(dict2.has_key('Place'))

Running the above code gives us the following result −

Output

True
False

dict.fromkeys(seq[, value]))

In this method we convert a sequence of values to a dictionary. We can also specify a value which become spart of every key.

Syntax

dict.fromkeys(seq)

In the below example we create a dictionary out of a sequence and add a value to it..

Example

 Live Demo

seq = {'Distnace','Temp','Humidity'}
dict = dict.fromkeys(seq)
   print(dict)
dict = dict.fromkeys(seq,15)
   print(dict)

Running the above code gives us the following result −

Output

{'Distnace': None, 'Humidity': None, 'Temp': None}
{'Distnace': 15, 'Humidity': 15, 'Temp': 15}

Updated on: 20-Dec-2019

351 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements