Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 224
user2989027 Avatar asked Nov 19 '13 18:11

user2989027


People also ask

How do you create a dictionary with keys and no values?

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.

Can a dictionary have a key with no value?

There is no such thing as a key without a value in a dict. You can just set the value to None, though.

Can you have a dictionary with no values in Python?

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.

Can a dictionary key have empty value Python?

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.


1 Answers

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) 
like image 95
codegeek Avatar answered Sep 28 '22 03:09

codegeek