我需要将Dict插入到Mysql数据库中并检索它。
为此我编写了如下代码:
# dict json dumped for inserting to DB
final_dict = json.dumps(big_dict)
invoice_id = tenant_id
# fina_dict exists
if final_dict:
logging.info("Inserting the necessary details into invoice_details table for tenant %s invoice period (%s to %s) Invoice date - %s" % (tenant_id, begin, end, date))
sql = "INSERT INTO invoice_details(invoice_date, tenant_id, invoice_id, invoice_data, invoice_period_from, invoice_period_to) \
VALUES ( '%s', '%s', '%s', '%s', '%s', '%s' )" % \
(date, tenant_id, invoice_id, final_dict, begin, end)
在上面的代码中,big_dict基本上是一个我需要插入DB的Dict。
因此我在同一个数据库中执行json.dump,以便在DB中插入相同的内容。
我可以看到它已根据需要插入到数据库中。
invoice_data: {"dict_all_cost_total": "16872.4061451", "dict_total_all": {"c3362ca0-8810-4ab7-a5b2-3cb571815690": ["test_instance", "m1.tiny", "16797.8795147"]}, "dict_inbound": {"c3362ca0-8810-4ab7-a5b2-3cb571815690": ["test_instance", "m1.tiny", "98.6362838745"]}, "dict_volume": "0", "dict_compute": {"c3362ca0-8810-4ab7-a5b2-3cb571815690": ["test_instance", "m1.tiny", "16570.0"]}, "dict_floating": "4.5", "dict_outbound": {"c3362ca0-8810-4ab7-a5b2-3cb571815690": ["test_instance", "m1.tiny", "129.24323082"]}}
现在我需要重新获取值并需要处理它们。
我已经设计了一些示例代码来获取值。
表示data_new中的数据:
data1 = json.loads(data)
print data1
print type(data1)
dict_compute = data1['dict_compute']
for dict_computes in dict_compute.iteritems():
for dict_computes_items in dict_computes:
print dict_computes_items
结果如下:
<type 'tuple'>
{u'dict_all_cost_total': u'109776.13801', u'dict_total_all': {u'5477b2b2-91f8-4e4b-a5b0-8f4a32210915': [u'instance_for_demo', u'm1.tiny', u'109776.13801']}, u'dict_inbound': {u'5477b2b2-91f8-4e4b-a5b0-8f4a32210915': [u'instance_for_demo', u'm1.tiny', u'93072.0652571']}, u'dict_volume': u'0', u'dict_compute': {u'5477b2b2-91f8-4e4b-a5b0-8f4a32210915': [u'instance_for_demo', u'm1.tiny', u'16590.0']}, u'dict_floating': u'0', u'dict_outbound': {u'5477b2b2-91f8-4e4b-a5b0-8f4a32210915': [u'instance_for_demo', u'm1.tiny', u'114.072752953']}}
<type 'dict'>
5477b2b2-91f8-4e4b-a5b0-8f4a32210915
[u'instance_for_demo', u'm1.tiny', u'16590.0']
我的目标是从dict_computes获取值。
instance_for_demo, m1.tiny etc
答案 0 :(得分:0)
您需要将json转换回dict结构:
+ 1.0 = 3.0
+ 2.0 = 5.0
+ 3.0 = 8.0
+ 1.0 = 4.0
+ 2.0 = 6.0
+ 3.0 = 9.0
1.0 + 3.0 = 4.0
+ 1.0 = 4.0
+ 2.0 = 6.0
+ 3.0 = 9.0
2.0 + 2.0 = 4.0
3.0 + 1.0 = 4.0