简体   繁体   中英

Accessing to a dictionary on a JSON in Python

I am trying to assign a value of a dictionary copied in JSON to a variable in my code.

This is the dictionary copied on the .json:

"Monetarios": [{"MIFID_NO_CURR_RISK":"B1"},{"MIFID_CURR_RISK":"B2"}],
          "Monetario Dinamico": [{"MIFID_NO_CURR_RISK":"B1"},{"MIFID_CURR_RISK":"B2"}],
          "Renta Fija Corto Plazo": [{"MIFID_NO_CURR_RISK":"B1"},{"MIFID_CURR_RISK":"B2"}],
          "Garantizados de RF": [{"MIFID_NO_CURR_RISK":"B1"},{"MIFID_CURR_RISK":"B2"}],
          "Renta Fija Largo Plazo": [{"MIFID_NO_CURR_RISK":"B1"},{"MIFID_CURR_RISK":"B2"}]

And I am trying to show on screen for example the B1 of MIFID NO CURR RISK from "Renta Fija Corto Plazo"

I do this and it works fine:

carga_dict['Renta Fija Corto Plazo']
Out[56]: [{u'MIFID_NO_CURR_RISK': u'B1'}, {u'MIFID_CURR_RISK': u'B2'}]

But then I do this, I get an error:

carga_dict['Renta Fija Corto Plazo']['MIFID_NO_CURR_RISK']
Traceback (most recent call last):

  File "<ipython-input-57-46b56ce8491a>", line 1, in <module>
    carga_dict['Renta Fija Corto Plazo']['MIFID_NO_CURR_RISK']

TypeError: list indices must be integers, not str
carga_dict['Renta Fija Corto Plazo'][0]['MIFID_NO_CURR_RISK']

carga_dict['Renta Fija Corto Plazo'] is a list of dictionary. so you have to first select the list element and find the appropriate key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM