Home > Back-end >  Get specific values out of dictionary with multiple keys in Python
Get specific values out of dictionary with multiple keys in Python

Time:12-05

I want to extract multiple ISINs out of a output.json file in python.

The output.json file looks like the following:

{'A1J780': {'ter': '0.20%', 'wkn': 'A1J780', 'isin': 'IE00B88DZ566'}, 'A1J7W9': {' 'ter': '0.20%', 'isin': 'IE00B8KMSQ34'}, 'LYX0VQ': {'isin': 'LU1302703878'}, 'A2AMYP': {'ter': '0.22%', 'savingsPlan': None, 'inceptionDate': '02.11.16', 'fundSize': '48', 'isin': 'IE00BD34DB16'}} ...

My current approach is the following:

 with open('output.json') as f:
        data = json.load(f)

    value_list = list()
    for i in data:
         value_list.append(i['isin'])
    print(value_list)

However, I receive the error message:

Traceback (most recent call last):
  File "/Users/placeholder.py", line 73, in <module>
    value_list.append(i['isin'])
                      ~^^^^^^^^
TypeError: string indices must be integers, not 'str'

I would highly appreciate your input!

Thank you in advance!

CodePudding user response:

Use data.values() as target in for loop to iterate over the JSON objects. Doing a loop over data iterates over the keys which is a string value (e.g. "A1J780").

data = {
    'A1J780': {'ter': '0.20%', 'wkn': 'A1J780', 'isin': 'IE00B88DZ566'},
    'A1J7W9': {'ter': '0.20%', 'isin': 'IE00B8KMSQ34'}
}
value_list = []
for i in data.values():
    value_list.append(i['isin'])
print(value_list)

Output:

['IE00B88DZ566', 'IE00B8KMSQ34']

If the isin key is not present in any of the dictionary objects then you would need to use i.get('isin') and check if the value is not None otherwise i['isin'] would raise an exception.

CodePudding user response:

The error message TypeError: string indices must be integers, not 'str' indicates that you are trying to access a dictionary value using a string as the key, but the type of the key should be an integer instead.

In your code, the i variable in the for loop is a string, because it represents the keys in the data dictionary. However, you are trying to access the 'isin' value in the dictionary using the i['isin'] syntax, which is not valid for a string key.

To fix this issue, you can use the i variable as the key to access the dictionary value, like this:

with open('output.json') as f:
    data = json.load(f)

value_list = list()
for i in data:
    value_list.append(data[i]['isin'])
print(value_list)

In this updated code, the data[i] syntax is used to access the dictionary value associated with the key i, and then the ['isin'] syntax is used to access the 'isin' value in the nested dictionary.

This code should produce the expected output of a list of ISINs from the output.json file.

  • Related