Problem
Consider the following list that we created out of a couple simple JSON strings that we transformed to Python dictionaries using the json.loads() function. As you can see the dictionary keys are string objects.
#python3
lang_lst = [{'language': 'Python', 'salary': 150},
{'language': 'R', 'salary': 130},
{'language': 'Julia', 'salary': 135},
]
Let us now assume that we would like to loop through the different list elements and print the different key value pairs for each programming language in the list.
When looping through the list in order to print the dictionaries key value pairs your Python IDE (Jupyter, PyCharm, VS Code, Spyder) will throw a type error.
for candidate in cand_lst:
print(cand_lst[key], cand_lst[value])
This will result in the following typeerror:
TypeError: list indices must be integers or slices, not str
Solution
The key reason for the type error that we received is that Python doesn’t allow us to access a specific index in a list using a string – only integers or integer ranges are allowed. This is of utmost importance. For example, such a code snippet won’t work for you:
my_list = []
my_list['Python'] = 'Very cool language'
Back to our example, In order to read the list values we’ll slightly modify our code.
#python3
# enumerate the list elements as tuples
for c, candidate in enumerate(cand_lst):
for key, value in candidate.items():
print (str(key) +":" + str (value))
This will effectively allow us to print the different key/value pairs included in the dictionaries in our Python list:
language:Python salary:150 language:R salary:130 language:Julia salary:135
This is a trivial example, but same technique applies to more complex Json data with nested dictionaries.