Different ways of adding to a dictionary in C#

The performance is almost a 100% identical. You can check this out by opening the class in Reflector.net This is the This indexer: public TValue this[TKey key] { get { int index = this.FindEntry(key); if (index >= 0) { return this.entries[index].value; } ThrowHelper.ThrowKeyNotFoundException(); return default(TValue); } set { this.Insert(key, value, false); } } And this … Read more

Method to add new or update existing item in C# Dictionary

Could there be any problem if i replace Method-1 by Method-2? No, just use map[key] = value. The two options are equivalent. Regarding Dictionary<> vs. Hashtable: When you start Reflector, you see that the indexer setters of both classes call this.Insert(key, value, add: false); and the add parameter is responsible for throwing an exception, when … Read more

Verify if a String is JSON in python?

The correct answer is: stop NOT wanting to catch the ValueError. Example Python script returns a boolean if a string is valid json: import json def is_json(myjson): try: json_object = json.loads(myjson) except ValueError as e: return False return True print(is_json(‘{}’)) # prints True print(is_json(‘{asdf}’)) # prints False print(is_json(‘{“age”:100}’)) # prints True print(is_json(‘{‘age’:100 }’)) # prints … Read more

Sqlite and Python — return a dictionary using fetchone()?

There is actually an option for this in sqlite3. Change the row_factory member of the connection object to sqlite3.Row: conn = sqlite3.connect(‘db’, row_factory=sqlite3.Row) or conn.row_factory = sqlite3.Row This will allow you to access row elements by name–dictionary-style–or by index. This is much more efficient than creating your own work-around.

Do Dictionaries have a key length limit?

There is no such limit in place regarding dictionary keys. Since python also has arbitrary precision on numeric types, the only limit you will encounter, string or otherwise, is that of available memory. You can see another post here for a discussion on maximum string length in python 2.

Find dictionary keys with duplicate values

First, flip the dictionary around into a reverse multidict, mapping each value to all of the keys it maps to. Like this: >>> some_dict = {“firstname”:”Albert”,”nickname”:”Albert”,”surname”:”Likins”,”username”:”Angel”} >>> rev_multidict = {} >>> for key, value in some_dict.items(): … rev_multidict.setdefault(value, set()).add(key) Now, you’re just looking for the keys in the multidict that have more than 1 value. … Read more