Swap around key and value (containing a list) within a Python dictionary -
i have reference dictionary subjects , page numbers so:
reference = { 'maths': [3, 24],'physics': [4, 9, 12],'chemistry': [1, 3, 15] }
i need writing function inverts reference. is, returns dictionary page numbers keys, each associated list of subjects. example, swap(reference) run on above example should return
{ 1: ['chemistry'], 3: ['maths', 'chemistry'], 4: ['physics'], 9: ['physics'], 12: ['physics'], 15: ['chemistry'], 24: ['maths'] }
you can use defaultdict
:
from collections import defaultdict d = defaultdict(list) reference = { 'maths': [3, 24],'physics': [4, 9, 12],'chemistry': [1, 3, 15] } a, b in reference.items(): in b: d[i].append(a) print(dict(d))
output:
{1: ['chemistry'], 3: ['maths', 'chemistry'], 4: ['physics'], 9: ['physics'], 12: ['physics'], 15: ['chemistry'], 24: ['maths']}
without importing collections
:
d = {} a, b in reference.items(): in b: if in d: d[i].append(a) else: d[i] = [a]
output:
{1: ['chemistry'], 3: ['maths', 'chemistry'], 4: ['physics'], 9: ['physics'], 12: ['physics'], 15: ['chemistry'], 24: ['maths']}
Comments
Post a Comment