I found the default implemtation of ToString in the dictionary is not what I want. I would like to have {key=value, ***}
.
Any handy way to get it?
You can easily convert a Python dictionary to a string using the str() function. The str() function takes an object (since everything in Python is an object) as an input parameter and returns a string variant of that object.
The serialization and deserialization of . NET objects is made easy by using the various serializer classes that it provides. But serialization of a Dictionary object is not that easy. For this, you have to create a special Dictionary class which is able to serialize itself.
If you just want to serialize for debugging purposes, the shorter way is to use String.Join
:
var asString = string.Join(Environment.NewLine, dictionary);
This works because IDictionary<TKey, TValue>
implements IEnumerable<KeyValuePair<TKey, TValue>>
.
Console.WriteLine(string.Join(Environment.NewLine, new Dictionary<string, string> { {"key1", "value1"}, {"key2", "value2"}, {"key3", "value3"}, })); /* [key1, value1] [key2, value2] [key3, value3] */
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