2013-06-11 8 views
85

मैं इस तरह एक dict है:अजगर डंप dict

sample = {'ObjectInterpolator': 1629, 'PointInterpolator': 1675, 'RectangleInterpolator': 2042} 

मैं समझ नहीं एक json फाइल करने के लिए dict डंप करने के लिए कैसे के रूप में नीचे दिखाया:

{  
    "name": "interpolator", 
    "children": [ 
     {"name": "ObjectInterpolator", "size": 1629}, 
     {"name": "PointInterpolator", "size": 1675}, 
     {"name": "RectangleInterpolator", "size": 2042} 
    ] 
} 

है ऐसा करने के लिए एक पाइथोनिक तरीका है?

आप अनुमान लगा सकते हैं कि मैं d3 ट्रेमैप उत्पन्न करना चाहता हूं।

उत्तर

8

यह आपको एक शुरुआत

>>> import json 
>>> print json.dumps([{'name': k, 'size': v} for k,v in sample.items()], indent=4) 
[ 
    { 
     "name": "PointInterpolator", 
     "size": 1675 
    }, 
    { 
     "name": "ObjectInterpolator", 
     "size": 1629 
    }, 
    { 
     "name": "RectangleInterpolator", 
     "size": 2042 
    } 
] 
15
d = {"name":"interpolator", 
    "children":[{'name':key,"size":value} for key,value in sample.items()]} 
json_string = json.dumps(d) 
बेशक

, यह संभावना नहीं है कि आदेश वास्तव में संरक्षित किया जाएगा ... लेकिन है कि बस शब्दकोशों का स्वभाव है देना चाहिए ...

+3

json_string = json.dumps (d,, sort_keys = True) अगर क्रमबद्ध क्रम वांछित है। –

16

कम्बाइन @mgilson और @gnibbler का जवाब, मैंने पाया कि मैं क्या जरूरत है इस था:

 

d = {"name":"interpolator", 
    "children":[{'name':key,"size":value} for key,value in sample.items()]} 
j = json.dumps(d, indent=4) 
f = open('sample.json', 'w') 
print >> f, j 
f.close() 
 

यह इस तरह से, मैं एक बहुत मिल गया -प्रिंट जेसन फ़ाइल। चाल print >> f, j यहां से पाया जाता है: http://www.anthonydebarros.com/2012/03/11/generate-json-from-sql-using-python/

+0

'प्रिंट (जे, फ़ाइल = एफ)' पायथन 3.6 में ('प्रिंट >> एफ, जे' के बजाय) – mjkrause

139
import json 
with open('result.json', 'w') as fp: 
    json.dump(sample, fp) 

यह यह करने के लिए एक आसान तरीका है।

कोड की दूसरी पंक्ति में फ़ाइल result.json को fp चर के रूप में बनाया और खोला जाता है।

तीसरी पंक्ति में आपके निर्देश sample को result.json में लिखा गया है!

+0

@ फर्मि परिणाम जेएसओएन एक को सॉर्ट किया गया है। क्या मैं इसे JSON –

+0

में डंप करते समय इस सॉर्टिन को रोक सकता हूं @ डेनिश पता नहीं है। जब तक आपकी समस्या के बारे में SO पर पहले से कोई प्रश्न नहीं है, तो आपको अपनी समस्या का वर्णन करने वाला एक नया प्रश्न बनाना चाहिए। (बीटीडब्ल्यू, मैं बस उन पदों का एक संपादक हूँ) –

+0

मैं भी नहीं जानता। फर्मि प्रस्तावित एक नए सवाल से पूछें। – moobi

संबंधित मुद्दे