1

I have a python dictionary which I want to convert into json.

Python dictionary:

{"20090209.02s1.1_sequence.txt": [645045714, 3559.6422951221466, 206045184], "20090209.02s1.2_sequence.txt": [645045714, 3543.8322949409485, 234618880]}

Desired output:

{
       "file_name":"20090209.02s1.1_sequence.txt",
       "file_information": [645045714, 3559.6422951221466, 206045184],

    {
       "file_name":"20090209.02s1.2_sequence.txt",
       "file_information": [645045714, 3543.8322949409485, 234618880],

    }
}

Tried with json.dumps but I didn't get the desired output.

pynovice
  • 7,424
  • 25
  • 69
  • 109

2 Answers2

16

You need to first create a structure with the correct format:

import json

dict_ = {"20090209.02s1.1_sequence.txt": [645045714, 3559.6422951221466, 206045184], "20090209.02s1.2_sequence.txt": [645045714, 3543.8322949409485, 234618880]}
values = [{"file_name": k, "file_information": v} for k, v in dict_.items()]
json.dumps(values, indent=4)

Note that the desired JSON output does not look valid to me. Here's the output for this code:

[
    {
        "file_name": "20090209.02s1.1_sequence.txt", 
        "file_information": [
            645045714, 
            3559.6422951221466, 
            206045184
        ]
    }, 
    {
        "file_name": "20090209.02s1.2_sequence.txt", 
        "file_information": [
            645045714, 
            3543.8322949409485, 
            234618880
        ]
    }
]
Bryce Siedschlaw
  • 4,136
  • 1
  • 24
  • 36
Samy Arous
  • 6,794
  • 13
  • 20
1

Split out your key-value pairs into separate dictionaries:

json.dumps([{'file_name': key, 'file_information': value} for key, value in yourdict.iteritems()])

Note that the order of your output will be arbitrary (dictionaries have no fixed ordering). You may want to sort the output to produce a predictable list:

from operator import itemgetter

data = [{'file_name': key, 'file_information': value} for key, value in yourdict.iteritems()]
data.sort(key=itemgetter('file_name'))
json.dumps(data)

This produces:

>>> data = [{'file_name': key, 'file_information': value} for key, value in yourdict.iteritems()]
>>> data.sort(key=itemgetter('file_name'))
>>> json.dumps(data)
'[{"file_name": "20090209.02s1.1_sequence.txt", "file_information": [645045714, 3559.6422951221466, 206045184]}, {"file_name": "20090209.02s1.2_sequence.txt", "file_information": [645045714, 3543.8322949409485, 234618880]}]'
>>> print json.dumps(data, indent=4)

[
    {
        "file_name": "20090209.02s1.1_sequence.txt",
        "file_information": [
            645045714,
            3559.6422951221466,
            206045184
        ]
    },
    {
        "file_name": "20090209.02s1.2_sequence.txt",
        "file_information": [
            645045714,
            3543.8322949409485,
            234618880
        ]
    }
]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343