迭代python字典为表的字段赋值

时间:2016-06-05 15:23:55

标签: python json dictionary

使用API​​我将json字典作为响应形式:

{"transacDet":[{"field1":6933434802,"field2":323499903,"field3":293483842},
{"field1":693433448,"field2":333400300,"field3":298334300}],"responseStatus"
:{"statusMessage":"success","statusCode":0}}

我希望在一个表中创建记录,该表具有与json响应中相同的相应字段:field1,field2,field3。

从上面的例子我将有2条记录:

field1 = 6933434802
field2 = 333400298
field3 = 298334842

然后:

field1 = 693433448
field2 = 333400300
field3 = 298334300

我必须迭代响应但不清楚如何。

我尝试使用:

for k in resp_json.items()[0][1][0]:
print k
但是我被困在那里了。 TIA

5 个答案:

答案 0 :(得分:2)

a= {"transacDet":[{"field1":6933434802,"field2":323499903,"field3":293483842},
{"field1":693433448,"field2":333400300,"field3":298334300}],"responseStatus"
:{"statusMessage":"success","statusCode":0}}

import pandas as pd

df =pd.DataFrame(a['transacDet'])

df
Out[11]: 
       field1     field2     field3
0  6933434802  323499903  293483842
1   693433448  333400300  298334300

迭代数据帧:

for i in df.iterrows(): print i[1], '\n'
field1    6933434802
field2     323499903
field3     293483842
Name: 0, dtype: int64 

field1    693433448
field2    333400300
field3    298334300
Name: 1, dtype: int64 

因此,如果您不想使用pandas。只需使用generator(list comprehension),这是基于@Dilettant的解决方案:

[(k, d[k]) for d in resp_json['transacDet'] for k in sorted(d.keys())]
Out[24]: 
[(u'field1', 6933434802L),
 (u'field2', 323499903),
 (u'field3', 293483842),
 (u'field1', 693433448),
 (u'field2', 333400300),
 (u'field3', 298334300)]

答案 1 :(得分:1)

只使用标准库中的json模块,您可以按照每个"行"的字段名称进行迭代。很容易这样:

#! /usr/bin/env
from __future__ import print_function
import json


JSON_TEXT = '''
{"transacDet":[{"field1":6933434802,"field2":323499903,"field3":293483842},
{"field1":693433448,"field2":333400300,"field3":298334300}],"responseStatus"
:{"statusMessage":"success","statusCode":0}}'''

resp_json = json.loads(JSON_TEXT)
for d in resp_json['transacDet']:
    for k in sorted(d.keys()):
        print(k, d[k])

哪个收益率:

field1 6933434802
field2 323499903
field3 293483842
field1 693433448
field2 333400300
field3 298334300

更新以草绘如何将这些值推送到INSERT调用中:

# inside the loop instead of iterating over the fields in the
# dict / row at hand, one could easily for instance do:
resp_json = json.loads(JSON_TEXT)
for d in resp_json['transacDet']:
    insert_row(**d)

这里insert_row将是一个定义如下的函数(样本):

def insert_row(**kwargs):
    """Not production ready ;-)."""
    # pick up the row key-value pairs from dict
    list_of_tuples = [
        (k, kwargs[k] for k in sorted(kwargs.keys())]
    pass  # here you might use this list of (k, v) tuples

答案 2 :(得分:0)

根据我的说法,你只需要迭代transacDet键:

import json
parsed = json.loads('{"transacDet":[{"field1":6933434802,"field2":323499903,"field3":293483842}, {"field1":693433448,"field2":333400300,"field3":298334300}],"responseStatus" :{"statusMessage":"success","statusCode":0}}')

for record in parsed['transacDet']:
    print record

结果:

{u'field2': 323499903, u'field3': 293483842, u'field1': 6933434802}
{u'field2': 333400300, u'field3': 298334300, u'field1': 693433448}

然后你可以把它发送到任何你想要的地方

答案 3 :(得分:0)

我认为resp_json已经是dict

因此,要访问字段dict的列表,您可以通过键引用它,而不是索引:

resp_json['transacDet']为您提供:

[{"field1":6933434802,"field2":323499903,"field3":293483842}, {"field1":693433448,"field2":333400300,"field3":298334300}]

然后你想要迭代这些,如下:

for values in resp_json['transacDet']:
    # here you can now access the content of the current `dict`
    print 'field1 = ' + values['field1']
    # would print: "field1 = 6933434802"
    # ... and so on

答案 4 :(得分:0)

试试这个:

a= {"transacDet":[{"field1":6933434802,"field2":323499903,"field3":293483842},
{"field1":693433448,"field2":333400300,"field3":298334300}],"responseStatus"
:{"statusMessage":"success","statusCode":0}}

import pandas as pd

df =pd.DataFrame(a['transacDet']).T

print df[0]
print df[1]



 #  field1    6933434802
  #  field2     323499903
  #  field3     293483842
  #  Name: 0, dtype: int64

  #  field1    693433448
  #  field2    333400300
  #  field3    298334300
  #  Name: 1, dtype: int64

import json

JSON_TEXT = '''
{"transacDet":[{"field1":6933434802,"field2":323499903,"field3":293483842},
{"field1":693433448,"field2":333400300,"field3":298334300}],"responseStatus"
:{"statusMessage":"success","statusCode":0}}'''

resp_json = json.loads(JSON_TEXT)


t1 = [[k,v] for k,v in  resp_json['transacDet'][0].iteritems()]
t2 = [[k,v] for k,v in  resp_json['transacDet'][1].iteritems()]      

 print (t1)
 print (t2)

   # [[u'field2', 323499903], [u'field3', 293483842], [u'field1', 6933434802]]
   # [[u'field2', 333400300], [u'field3', 298334300], [u'field1', 693433448]]