Q:

Python: Dictionary into Json file

I have the following dictionary
a = {'index': [1, 2, 3], 'similar': [[0, 2], [1, 2], [2, 1]], 'markets': [['A', 'C'], ['B', 'C'], ['A', 'B']]}
keys = ['index', 'similar', 'markets']

And I want it to transform it into a json file
like
{'index': 'elem1' , "similar" :  [ {'elem0' 'elem2'} ]  , "markets" : [{'marketA', 'marketC'}] }
{'index': 'elem2  , "similar" :  [ {'elem1' 'elem2'} ]  , "markets" : [{'marketB', 'marketC'}] }
{'index': 'elem3' , "similar" :  [ {'elem2' 'elem1'} ]  , "markets" : [{'marketA', 'marketB'}] }

I currently have
with open('result.json', 'w') as fp:
    json.dump(a, fp)

But I am not sure how to get the desired outcome
Any help would be much appreciated

A:

You will have to adapt the structure of your currently desired output. Your similar and market arrays contain sets ([{'elem0', 'elem2' }]) which is of course not possible in JSON.
I have written the necessary piece of code for you.
import json
f = {'index': [1, 2, 3], 'similar': [[0, 2], [1, 2], [2, 1]], 'markets': [['A', 'C'], ['B', 'C'], ['A', 'B']]}
res = {}
for k,v in f.iteritems():
    for i, s_v in enumerate(v):
        if not res.get(i):
            res[i] = {}
        if k == 'markets':
            prefix = 'market'
        else:
            prefix = 'elem'
        if isinstance(s_v, int):
            res[i][k] = '%s%s' % (prefix, s_v)
        else:
            res[i][k] = [[]]
            for _s_v in s_v:
                res[i][k][0].append('%s%s' % (prefix, _s_v))
            res[i][k][0] = res[i][k][0]
res = [v for k, v in res.iteritems()]
print json.dumps(res)

.. [{"index": "elem1", "similar": [["elem0", "elem2"]], "markets": [["marketA", "marketC"]]}, {"index": "elem2", "similar": [["elem1", "elem2"]], "markets": [["marketB", "marketC"]]}, {"index": "elem3", "similar": [["elem2", "elem1"]], "markets": [["marketA", "marketB"]]}]

