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.
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.
You can copy code here.
x = (‘key1’, ‘key2’, ‘key3’)
y = 1
dictionary = dict.fromkeys(x, y)
- A tuple with some keys is being taken.
- A variable ‘y’ with value 1 is being taken which will be passed as value.
- Type of variable is printed.
- 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.
- Value of the dictionary is printed.
- Type of variable x printed which is tuple.
- Value of the dictionary is printed with certain keys and values.
- 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.