Home > Net >  dict.get() giving TypeError
dict.get() giving TypeError

Time:04-15

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.

CodePudding user response:

The get method is a method of python dictionary. Its input is key and (optional) value that should be return if key does not exist.

[] Is another syntax for accessing dictionary values. You can think of it as another method of dictionary (in real it calls __getitem__ method).

So when you write input_data["level1"] you get value for key "level" which is list so you use result of it as list

mylist = input_data["level1"] # it returns list
first_el = my_list[0] # this is dict again!
level2 = first_el["level2"] # and list again
# it's the same as input_data["level1"][0]["level2"]

Saying that, you could replace all dictionary accesses with get call

mylist = input_data.get("level1")
first_el = my_list[0] # this is list and have no get method
level2 = first_el.get("level2")
# it's the same as input_data.get("level1")[0].get("level2")
  • Related