I was wondering if there was a way to initialize a dictionary in python with keys but no corresponding values until I set them. Such as:
Definition = {'apple': , 'ball': }
and then later i can set them:
Definition[key] = something
I only want to initialize keys but I don't know the corresponding values until I have to set them later. Basically I know what keys I want to add the values as they are found. Thanks.
In Python to create an empty dictionary with keys, we can use the combination of zip() and len() method. This method will initialize a dictionary of keys and returns no values in the dictionary.
There is no such thing as a key without a value in a dict. You can just set the value to None, though.
Yes, sets : set() -> new empty set object set(iterable) -> new set object Build an unordered collection of unique elements. Related: How is set() implemented? Show activity on this post.
In Python, we can use the zip() and len() methods to create an empty dictionary with keys. This method creates a dictionary of keys but returns no values from the dictionary.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With