Initializing a dictionary in python with a key value and no corresponding values

Use the fromkeys function to initialize a dictionary with any default value. In your case, you will initialize with None since you don’t have a default value in mind.

empty_dict = dict.fromkeys(['apple','ball'])

this will initialize empty_dict as:

empty_dict = {'apple': None, 'ball': None}

As an alternative, if you wanted to initialize the dictionary with some default value other than None, you can do:

default_value="xyz"
nonempty_dict = dict.fromkeys(['apple','ball'],default_value)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)