Python dictionary from an object’s fields

Note that best practice in Python 2.7 is to use new-style classes (not needed with Python 3), i.e. class Foo(object): … Also, there’s a difference between an ‘object’ and a ‘class’. To build a dictionary from an arbitrary object, it’s sufficient to use __dict__. Usually, you’ll declare your methods at class level and your attributes … Read more

Get dictionary key by value

Values do not necessarily have to be unique, so you have to do a lookup. You can do something like this: var myKey = types.FirstOrDefault(x => x.Value == “one”).Key; If values are unique and are inserted less frequently than read, then create an inverse dictionary where values are keys and keys are values.

How to pretty print nested dictionaries?

My first thought was that the JSON serializer is probably pretty good at nested dictionaries, so I’d cheat and use that: >>> import json >>> print(json.dumps({‘a’:2, ‘b’:{‘x’:3, ‘y’:{‘t1’: 4, ‘t2’:5}}}, … sort_keys=True, indent=4)) { “a”: 2, “b”: { “x”: 3, “y”: { “t1”: 4, “t2”: 5 } } }

Is there any advantage of using map over unordered_map in case of trivial keys?

Don’t forget that map keeps its elements ordered. If you can’t give that up, obviously you can’t use unordered_map. Something else to keep in mind is that unordered_map generally uses more memory. map just has a few house-keeping pointers, and memory for each object. Contrarily, unordered_map has a big array (these can get quite big … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)