Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load values into Dictionary using { }

Is is possible to load values into Dictionary using { } ?

This fails

static Dictionary<byte, byte> dict = new Dictionary<byte, byte>() { new KeyValuePair<byte, byte>(1, 1) };

This does not fail so I suspect there is syntax for loading in { }

static Dictionary<byte, byte> dic1252expand = new Dictionary<byte, byte>() { };

This is sample syntax that works

byte[] bytes = new byte[] { 1, 2, 3 }; 
KeyValuePair<byte, byte> kvp = new KeyValuePair<byte, byte>(1, 1);
like image 850
paparazzo Avatar asked Apr 24 '13 13:04

paparazzo


People also ask

How do you add values to a dictionary in python?

There is no add() , append() , or insert() method you can use to add an item to a dictionary in Python. Instead, you add an item to a dictionary by inserting a new index key into the dictionary, then assigning it a particular value.


3 Answers

If you give someone a fish, they have a fish; if you teach them how to catch fish, you don't need to give them fish. All the answers posted are correct, but none tells you how to figure out the answer for yourself.

The collection initializer syntax in C# is a "syntactic sugar"; it is just a more pleasant way to write some boring code. When you write:

C c = new C() { p, q, { r, s }, {t, u, v} };

That is the same as if you had written:

C c;
C temporary = new C();
temporary.Add(p);
temporary.Add(q);
temporary.Add(r, s);
temporary.Add(t, u, v);
c = temporary;

Now it should be clear how you can figure out what to put in the initializer clause: look at the type and see what the various Add methods take as arguments. In your case, the dictionary's Add method takes a key and a value, so the initializer should be { { k1, v1 }, { k2, v2 } , ... }

Make sense?

like image 110
Eric Lippert Avatar answered Oct 21 '22 14:10

Eric Lippert


This is working:

Dictionary<byte, byte> dict = new Dictionary<byte, byte>() { { 1, 1 }, { 2, 2 } };
like image 34
Hossein Narimani Rad Avatar answered Oct 21 '22 14:10

Hossein Narimani Rad


Dictionary<string, string> d = new Dictionary<string, string>{{"s", "s"}};
like image 24
Oscar Avatar answered Oct 21 '22 12:10

Oscar