What is the most pythonic way to iterate over OrderedDict

You can use tuple unpacking in for statement: for i, (key, value) in enumerate(a.iteritems()): # Do something with i, key, value >>> d = {‘a’: ‘b’} >>> for i, (key, value) in enumerate(d.iteritems()): … print i, key, value … 0 a b Side Note: In Python 3.x, use dict.items() which returns an iterable dictionary view. … Read more

Enum and performance

Casting from int to an enum is extremely cheap… it’ll be faster than a dictionary lookup. Basically it’s a no-op, just copying the bits into a location with a different notional type. Parsing a string into an enum value will be somewhat slower. I doubt that this is going to be a bottleneck for you … Read more

Converting list of tuples into a dictionary

>>> from collections import defaultdict >>> l= [(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)] >>> d= defaultdict( list ) >>> for v, k in l: … d[k].append(v) … >>> d defaultdict(<type ‘list’>, {23: [6, 7, 8, 10], 4: [1, 2, 3], 15: [4, 5, 9, 11, 12]}) >>> [ {k:d[k]} for k in sorted(d) ] [{4: [1, 2, 3]}, {15: [4, … Read more

objects as keys in python dictionaries

From the python documentation: A dictionary’s keys are almost arbitrary values. Values that are not hashable, that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys. Hashable is defined as follows An object is hashable if it has a … Read more

Using Dictionary get method to return empty list by default returns None instead

To solve this you should use Python’s defaultdict. The first time you use a key that doesn’t exist, the argument to the defaultdict constructor is used to create a value (in this case, a list). http://docs.python.org/library/collections.html#defaultdict-examples from collections import defaultdict d = defaultdict(list) for i in range( 0, 10 ): for j in range( 0, … Read more

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