Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping a table with a compound primary key to a python dictionary

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?

like image 946
Roland Avatar asked Dec 04 '25 11:12

Roland


1 Answers

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.

like image 55
u354356007 Avatar answered Dec 07 '25 01:12

u354356007