fromkeys(): creates a new dictionary with specified keys

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
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com







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 Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer