如何在Python中从平面表创建嵌套哈希?

时间:2017-12-13 18:03:34

标签: python

我是Python语言的新手。我遇到了一个问题,即我需要在Python中从平面表生成嵌套哈希。 需要实际输出:

{
    rid:'prkattim',
    'rname':'prashant',
    'proj':[
                {
                    'proid':P0123,
                    'proname':'Colgate Challenge',
                    'allocs':[
                                {
                                    'allocid':'Alloc1',
                                    'allocinfo':'Allocation for month 12',
                                    'price':26
                                },
                                {
                                    'allocid':'Alloc2',
                                    'allocinfo':'Allocation for month 11',
                                    'price':26
                                },
                                {
                                    'allocid':'Alloc3',
                                    'allocinfo':'Allocation for month 10',
                                    'price':24
                                }
                            ]
                },
                {
                    'proid':P0124,
                    'proname':'Ramoji Film city challenge',
                    'allocs':[
                                {
                                    'allocid':'Alloc1',
                                    'allocinfo':'Allocation for month 10',
                                    'price':120
                                }
                            ]
                }   
            ]
}

SQL表看起来像这样

id      rid         rname       proid       proname                 allocid         allocinfo           proce
'1'  'prkattim'  'prashant'  'P0123'  'Colget challenge'            'Alloc1'  'Allocation for month 12'  '25'
'2'  'prkattim'  'prashant'  'P0123'  'Colget challenge'            'Alloc2'  'Allocation for month 11'  '26'
'3'  'prkattim'  'prashant'  'P0123'  'Colget challenge'            'Alloc3'  'Allocation for month 10'  '24'
'4'  'prkattim'  'prashant'  'P0124'  'Ramoji Film city challenge'  'Alloc1'  'Allocation for month 10'  '120'

DB flat table view

请帮我逻辑一下。提前谢谢。

1 个答案:

答案 0 :(得分:1)

输出格式称为json,在python中非常容易使用。 我已经编写了简短的示例代码来向您展示如何执行此操作。

import json

# create json object and give it attributes "rid", "rname", and "proj" which is an array
data = {}
data["rid"] = "prkattim"
data["rname"] = "prashant"
data["proj"] = [] # in an array you will store other json object

# you can also use variables to as keys and values
for i in range(3):
    proj = {} 
    proj[i] = i*5
    data["proj"].append(proj) # append json object in json array


print json.dumps(data, indent=4,sort_keys=True)
# print and save data
with open('data.txt', 'w') as outfile:  
    json.dump(data, outfile)

现在你只需循环遍历你的表并创建数据的json对象。