fromkeys() method for dictionary

All dictionary methods

fromkeys(), takes keys and values( optional ) argument ( inputs ) .

Returns : new dictionary.

fromkeys() with keys and values

my_keys=('a','b','c') # using a tuple
my_values=('ONe','Two','Three')
my_dict=dict.fromkeys(my_keys,my_values)
print(my_dict)
Output is here
{'a': ('ONe', 'Two', 'Three'), 'b': ('ONe', 'Two', 'Three'), 
	'c': ('ONe', 'Two', 'Three')}

fromkeys() with keys only

my_keys=('a','b','c') # using a tuple
my_dict=dict.fromkeys(my_keys)
print(my_dict)
Output
{'a': None, 'b': None, 'c': None}

fromkeys() with single value only

my_keys=('a','b','c') # using a tuple
my_values=('One')
my_dict=dict.fromkeys(my_keys,my_values)
print(my_dict)
Output
{'a': 'One', 'b': 'One', 'c': 'One'}

fromkeys() with range

range() function returns sequence of numbers ( Immutable ) by taking start ( default =0 ) , stop( before ) and step ( Optional )
Here start value is 1, stop value is 6 (so before 6 it will stop) and default increment value is 1.
my_keys=range(1,6) # using a range to get sequence of keys
my_dict=dict.fromkeys(my_keys)
print(my_dict)
Output
{1: None, 2: None, 3: None, 4: None, 5: None}
We can assign value to any key
my_dict[2]='Two'
print(my_dict)
Output
{1: None, 2: 'Two', 3: None, 4: None, 5: None}

All dictionary methods
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer