I'm getting a TypeError when using the dict.get() function. Below is an example of the input:
input_data = {
"level1": [
{
"level2": [
{
"hn": "hn_example1",
"mi": ["mi1"]
},
{
"hn": "hn_example2",
"mi": ["mi2"]
}
]
}
],
}
When using the standard [] extraction, the result is as expected:
for output in input_data["level1"][0]["level2"]:
print(output)
>> {'hn': 'hn_example1', 'sv': ['sv1']}
>> {'hn': 'hn_example2', 'sv': ['sv2']}
But when using .get(), it gives a TypeError:
for output in input_data.get(["level1"][0]["level2"], []):
print(output)
TypeError: string indices must be integers
Can anyone explain why this is? I was under the impression that dict.get() returns the same result as dict[], except in the case where the key doesn't exist, in which case it would return the default value (in this case an empty list). An in any case type(input_data["level1"][0]) returns a dict, not a string.
Just a note that print(input_data.get(["level1"][0]["level2"], [])) gives the same result, it's just that in this usecase I need to access the values one at a time.
source https://stackoverflow.com/questions/71862858/dict-get-giving-typeerror
Comments
Post a Comment