Dictionary fromkeys() method Python

The Python dictionary fromkeys() method can create new dictionary.It accept one or two arguments and it can accept only iterable object.

If only one argument is passed the keys of the new dictionary is taken from the first argument and the value is assigned as ‘None’;which is the default value.If two arguments are passed the key is created from the first argument and the second argument is taken as the value.Well all the key have the same value in this case.

>>> d={}
>>> d1=d.fromkeys( 'Text' )
>>> d1
{'T': None, 'e': None, 'x': None, 't': None}
>>> d2=d.fromkeys( 'Text' , 'Values' )
>>> d2
{'T': 'Values', 'e': 'Values', 'x': 'Values', 't': 'Values'}
>>> d3=d.fromkeys( 'text' , d )
>>> d3
{'t': {}, 'e': {}, 'x': {}}

As you can see even if another dictionary is passed as the second argument the entire dictionary is taken as the value for each of the key of newly created dictionary.

If we pass another dictionary as the first argument then the key are taken as the key for the new dictionary.This also happen if we pass a list or a tuple as the first argument.

>>> ls=[23 ,56 ,78 ,89] #list 
>>> d={ 'Nm':'NM' ,'Hap':'HAP' , '010':'010102'} 
>>> tp=( 34 ,78 , 'TEXT') #tuple
>>> #Passing list as the first argument
>>> d1=d.fromkeys( ls  , 'New')
>>> d1
{23: 'New', 56: 'New', 78: 'New', 89: 'New'}
>>> #Passing dictionary as the first argument
>>> d2=d.fromkeys( d , 'NBW' )
>>> d2
{'Nm': 'NBW', 'Hap': 'NBW', '010': 'NBW'}
>>> #Passing tuple as the first argument
>>> d3=d.fromkeys( tp , 'Tuple' )
>>> d3
{34: 'Tuple', 78: 'Tuple', 'TEXT': 'Tuple'}


Leave a Reply

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