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);
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.
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?
This is working:
Dictionary<byte, byte> dict = new Dictionary<byte, byte>() { { 1, 1 }, { 2, 2 } };
Dictionary<string, string> d = new Dictionary<string, string>{{"s", "s"}};
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