Methods and Functions

Python Dictionary fromkeys()

Just like the string class methods, Python provides us with different class methods for the dictionary iterable. These functions can be used for handling dictionary related issues. It is sometimes necessary to generate a dictionary from the given keys. These key values might be provided in the form of iterables. It would take more time and effort to implement this manually. To solve this purpose Python fromkeys(), a dictionary class method is used. This article explains about Python fromkeys() function and its various aspects.

Python fromkeys() function

Definition

  • The Python fromkeys() built-in function generates a new dictionary from the specified sequence of elements as keys and a user-supplied value.
  • Python fromkeys() dictionary class method is used to create and return a new dictionary from a passed set of sequences as keys along with a value provided by the user.

Python’s fromkeys() is a class method in the dict class. It’s used to make a new dictionary out of an iterable. The iterable provides the keys for the new dictionary, while we offer a value to be mapped to the keys. If no value is provided, the keys are set to None by default.

fromkeys() Syntax

The syntax for Python fromkeys() is as follows:

                    

dict.fromkeys(sequence, value)

Note – Here, dict is a keyword and should not be changed.

fromkeys() Parameters

Python fromkeys() function accepts 2 parameters:

  • sequence – the sequence of elements/ an iterable (list, tuple, string, set) which are to be used as keys for creating a new dictionary
  • value (Optional) – specific value that is to be assigned to every key of the dictionary

Note – If no value is provided, the keys are set to None by default.

Return value from fromkeys()

It returns a new dictionary with the given sequence of elements as the dictionary’s keys. If the value parameter is used, the provided value is assigned to each element of the newly constructed dictionary.

If no value is specified, the keys are assigned None as their default values.

Example 1: Create a dictionary from a sequence of keys

Example

                    

# Python program to illustrate fromkeys()
# list iterable with city names as keys
city = ['London', 'New York', 'Mumbai', 'Shanghai', 'Tokyo']
my_dict = dict.fromkeys(city)
print(my_dict)

# set iterable with even numbers as keys
num = {2, 4, 6, 8, 10}
my_dict = dict.fromkeys(num)
print(my_dict)

Output

                    

{'London': None, 'New York': None, 'Mumbai': None, 'Shanghai': None, 'Tokyo': None}
{2: None, 4: None, 6: None, 8: None, 10: None}

Example 2: Create a dictionary from a sequence of keys with value

Example

                    

# Python program to illustrate fromkeys()
# list iterable with city names as keys
city = ['London', 'New York', 'Mumbai', 'Shanghai', 'Tokyo']
val = 'City'
my_dict = dict.fromkeys(city, val)
print(my_dict)

# set iterable with even numbers as keys
num = {2, 4, 6, 8, 10}
val = 'Even num'
my_dict = dict.fromkeys(num, val)
print(my_dict)

Output

                    

{'London': 'City', 'New York': 'City', 'Mumbai': 'City', 'Shanghai': 'City', 'Tokyo': 'City'}

{2: 'Even num', 4: 'Even num', 6: 'Even num', 8: 'Even num', 10: 'Even num'}

Example 3: Create a dictionary from mutable object list

Example

                    

letters = {'a', 'e', 'i', 'o', 'u'}

val = [0]
my_dict = dict.fromkeys(letters, val)
print('Newly created dictionary:', my_dict)

val.append(5)
print('Dictionary after appending:', my_dict)

Output

                    

Newly created dictionary: {'o': [0], 'u': [0], 'a': [0], 'e': [0], 'i': [0]}

Dictionary after appending: {'o': [0, 5], 'u': [0, 5], 'a': [0, 5], 'e': [0, 5], 'i': [0, 5]}

Python fromkeys() can also be given a mutable object as the default value. However, in this situation, a deep copy of the dictionary is created, which means that if we append a value to the original list, the append occurs in all key values. This is due to the fact that each element is given a reference to the same object (points to the same object in the memory). We use dictionary comprehension to prevent this problem.

Example

                    

letters = {'a', 'e', 'i', 'o', 'u'}

val = [0]
my_dict = {key:list(val) for key in letters}
print('Newly created dictionary:', my_dict)

val.append(5)
print('Dictionary after appending:', my_dict)

Output

                    

Newly created dictionary: {'a': [0], 'i': [0], 'o': [0], 'u': [0], 'e': [0]}

Dictionary after appending: {'a': [0], 'i': [0], 'o': [0], 'u': [0], 'e': [0]}

In this case, a new list of values is formed and assigned to each key in letters. In essence, val is not allocated to the element, but rather a new list is formed from it and assigned to each element in the dictionary.

Frequently Asked Questions

Q1. What does fromkeys do in Python?

It is sometimes necessary to generate a dictionary from the given keys. These key values might be provided in the form of iterables. To solve this purpose Python fromkeys(), a dictionary class method is used. The Python fromkeys() built-in function generates a new dictionary from the specified sequence of elements as keys and a user-supplied value.

Q2. How do you use the fromkeys() method in Python?

Python’s fromkeys() is a class method in the dict class. It’s used to make a new dictionary out of an iterable. The syntax for Python fromkeys() is as follows:

                    

dict.fromkeys(sequence, value)

Note – Here, dict is a keyword and should not be changed.

Example

                    

names = ['Sam', 'Tim', 'Leah', 'Kelly']
course = 'Masters'

my_dict = dict.fromkeys(names, course)
print(my_dict)

Output

                    

{'Sam': 'Masters', 'Tim': 'Masters', 'Leah': 'Masters', 'Kelly': 'Masters'}

Q3. Which value is assigned to the keys if no value is specified with the fromkeys() method?

In Python fromkeys() we also specify the value parameter. This value parameter is used to assign a value to each and every key of the dictionary. But if no value is specified, then the keys are assigned None as their default values.

Example

                    

numbers = [1, 2, 3, 4, 5]
my_dict = dict.fromkeys(numbers)
print(my_dict)

Output

                    

{1: None, 2: None, 3: None, 4: None, 5: None}

Q4. What is get() in Python?

Python get() is another built-in dict class function that is used to return a value for the specified key if the key exists in the dictionary. If the value is not present in the dictionary, then the get() function will return None.

Syntax:

                    

dict_name.get(key, value)

Example

                    

stud = {'Name': 'Sean', 'Age': 24, 'Course': 'MBA', 'City': 'California'}

print('Name of the student:', stud.get('Name'))
print('Course opted by the student:', stud.get('Course'))

# value not provided
print('Salary of the student:', stud.get('Salary'))

# value provided
print('Salary of the student:', stud.get('Salary', 0))

Output

                    

Name of the student: Sean
Course opted by the student: MBA
Salary of the student: None
Salary of the student: 0

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

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

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.