How to Use Dictionary fromkeys() Method in PythonPython Basics


The fromkeys() function is used to create a new dictionary, with the elements in the sequence seq as the keys and the value as the initial value corresponding to all keys.

Example

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

seq = ('name', 'age', 'sex','address','ID')

dict1 = dict.fromkeys(seq)
print("the dict1 is : ", dict1 )

dict2 = dict.fromkeys(seq, 2019)
print("the dict2 is: " ,dict2)

Output:

the dict1 is :  {'name': None, 'age': None, 'sex': None, 'address': None, 'ID': None}
the dict2 is:  {'name': 2019, 'age': 2019, 'sex': 2019, 'address': 2019, 'ID': 2019}

Syntax

dictionary.fromkeys(seq[, value])

Parameters

Name Description
seq The sequence of elements which is to be used as keys for the new dictionary.
value The value which is corresponding to all keys.

Return Value

It returns a new dictionary.

© 2024 Learnwithgpt.org, all rights reserved. Privacy Policy | Contact Us