I've got some data which originally looks like this which I'd like to process in Python 2.7:
id year value
1 2012 5
2 2012 50
3 2012 500
1 2013 6
2 2013 60
3 2013 600
1 2014 7
2 2014 70
3 2014 700
I can easily transform it into a list like this [[1,2012,5],[2,2012,6],...].
I'd like to convert this to a dictionary, as I'd like to look up all different values for a fixed id and/or year (If this idea is not so great and I should rather keep it as a list, please let me know in the comments.)
I know that a python dictionary needs a hashable key, so I could transform this table by concatenating id and year to a string and have a dictionary like
{'1_2012':'5','2_2012':'50', ...}
Obviously, this is not very elegant if you want to read out the separate parts of the key. What's the easiest way to get a compound key dictionary which is still easily dumpable into a json?
tuple is hashable:
{(1, 2012): 5, (2, 2012): 50,}
However, this dict cannot be dumped, the dict key in this case should be a string:
import json
import ast
# Works if keys satisfy following requirement:
# key == ast.literal_eval(repr(key))
# This is true for tuples having numbers inside.
def dumps(d):
return json.dumps({repr(key): value for key, value in d.items()})
def loads(s):
d = json.loads(s)
return {ast.literal_eval(key): value for key, value in d.items()}
This pair of function should go until you start using keys that are complex enough and/or that have their __repr__ method implemented poorly.
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