What is fromkeys() method in dictionary | How to use the fromkeys() method of a dictionary.

Definition:

This method is used to return a dictionary with specified keys and specified values. Keys can be stored in the form of an iterable object be it list, tuple or set. But most probably tuples are preferred. Also, value cannot be passed using an iterable object.

Syntax:

Keys = ()

Values = x

Dictionary = dict.fromkeys(x, y) 

This method takes two argument keys and values

Keys: Any iterable object be it list, tuple or sets

Values: A single value be it integer, string or Boolean.

Working:

forkeys()_method_dictionary

forkeys_methods_output

You can copy code here.

x = (‘key1’, ‘key2’, ‘key3’)
y = 1
print(type(x))
dictionary = dict.fromkeys(x, y)
print(dictionary)

Code:

  1. A tuple with some keys is being taken.
  2. A variable ‘y’ with value 1 is being taken which will be passed as value.
  3. Type of variable is printed.
  4. A variable named dictionary is taken and a constructor is used to typecast the dictionary variable into an empty dictionary. Also, fromkeys() method is applied and x values and y values are passed as an argument.
  5. Value of the dictionary is printed.

Output:

  1. Type of variable x printed which is tuple.
  2. Value of the dictionary is printed with certain keys and values.

Interview questions:

  • Can we pass dynamic values using the fromkeys() method?

No, to pass dynamic values we need an iterable object to pass as value, and fromkeys() method does not accept an iterable object as argument it only accepts a single value. But, to pass dynamic value we can write loops and different methods.

Related Article:

Waqar Khan

Hello, everyone, I am Waqar Khan. I have done my B.tech in Computer Science. I love to write about Computer Informational blogs. Before write I did proper research on it. Hope you like our blogs. Thank you.

Related Posts

Leave a Reply

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