Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How add key to dictionary without value?

Tags:

in normally we should add key and value together in dictionary type. like:

myDict.Add(key1, value1); myDict.Add(key2, value2); 

I want to know, Is there any way to add key first, then insert its value? (not both of them at the same time)

like image 873
Iran_Girl Avatar asked Sep 08 '13 15:09

Iran_Girl


People also ask

How do you add a key to a dictionary Python if not exists?

Add an item only when the key does not exist in dict in Python (setdefault()) In Python, you can add a new item to the dictionary dict with dict_object[key] = new_value . In this way, if the key already exists, the value is updated (overwritten) with the new value.

Can you create a dictionary without values?

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.

How do you assign a null to a dictionary key?

If the value type of the dictionary is nullable, you could add a null value: myDict. Add(key1, null); If the value is non nullable, you can use a default value, either default or some out of range value, depending on your expected meaningful values.

Can a dictionary have null value?

Dictionaries can't have null keys.


1 Answers

If the value type of the dictionary is nullable, you could add a null value:

myDict.Add(key1, null); 

If the value is non nullable, you can use a default value, either default or some out of range value, depending on your expected meaningful values.

myDict.Add(key1, default(int)); myDict.Add(key1, Int32.MinValue); 

But

as mentioned in the comments, there is no discernible merit in doing this. You can add values at any time, there is no need to pre-initialize a dictionary with keys.

like image 86
Rotem Avatar answered Oct 02 '22 10:10

Rotem