Eastwood
Eastwood

Reputation: 77

Retrieving data from nested dict in python

i'm trying to parse data from a dict. following is the dict.

data = {'specs': u'{"software_addon": None, 
"checkout_os": 
    {12L: {"status": 3L, "units": 1L, "label": "Disk1", "orderproduct_id": 22L, "slider_id": 788L, "unitPrice": 0.3}, 
    15L: {"status": 3L, "units": 60L, "label": None, "orderproduct_id": 22L, "slider_id": 787L, "unitPrice": 0.3}}, 
"checkout_op": {"pk": 11L, "total_price": 90.3, "discount_price": 80.3, "monthly_fee": 80.3}, 
"virtualmachine_vm": {"pk": 15L, "diskGB": 101L, "memoy_size": 3221225472L, "num_cpu": 2L}, 
"checkout_o": {"pk": 74L, "grand_total": 180.3, "discount_price": 180.3}
}', 
'id': 411L, 'name': u'name-7xccf'}

when i would try to retrieve the data it gives the error.

print data['specs']['virtualmachine_virtualmachines']['pk']

error: string indices must be integers, not str

Upvotes: 0

Views: 31

Answers (1)

Ronald
Ronald

Reputation: 2872

I tried it and got the same error as you (even with Eastwood's suggestion), but it worked after eliminating the u' and the corresponding closing quote. Obviously one can't use this u operator/modifier for an entire dict.

So

data = {'specs': {"software_addon": None, "checkout_os": {12L: {"status": 3L, "units": 1L, "label": "Disk1", "orderproduct_id": 22L, "slider_id": 788L, "unitPrice": 0.3}, 15L: {"status": 3L, "units": 60L, "label": None, "orderproduct_id": 22L, "slider_id": 787L, "unitPrice": 0.3}}, "checkout_op": {"pk": 11L, "total_price": 90.3, "discount_price": 80.3, "monthly_fee": 80.3}, "virtualmachine_vm": {"pk": 15L, "diskGB": 101L, "memory_size": 3221225472L, "num_cpu": 2L}, "checkout_o": {"pk": 74L, "grand_total": 180.3, "discount_price": 180.3} }, 'id': 411L, 'name': u'name-7xccf'}
print data['specs']['virtualmachine_vm']['pk']

worked

Upvotes: 1

Related Questions