Convert a namedtuple into a dictionary

TL;DR: there’s a method _asdict provided for this. Here is a demonstration of the usage: >>> from collections import namedtuple >>> fields = [‘name’, ‘population’, ‘coordinates’, ‘capital’, ‘state_bird’] >>> Town = namedtuple(‘Town’, fields) >>> funkytown = Town(‘funky’, 300, ‘somewhere’, ‘lipps’, ‘chicken’) >>> funkytown._asdict() {‘name’: ‘funky’, ‘population’: 300, ‘coordinates’: ‘somewhere’, ‘capital’: ‘lipps’, ‘state_bird’: ‘chicken’} This is … Read more

JSON serialize a dictionary with tuples as key

You can’t serialize that as json, json has a much less flexible idea about what counts as a dict key than python. You could transform the mapping into a sequence of key, value pairs, something like this: import json def remap_keys(mapping): return [{‘key’:k, ‘value’: v} for k, v in mapping.iteritems()] … json.dumps(remap_keys({(1, 2): ‘foo’})) >>> … Read more

Why can’t I use a list as a dict key in python? Exactly what can and cannot be used, and why?

There’s a good article on the topic in the Python wiki: Why Lists Can’t Be Dictionary Keys. As explained there: What would go wrong if Python allowed using lists as keys, say, using their memory location as the hash? It would cause some unexpected behavior. Lists are generally treated as if their value was derived … Read more

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