Why dict.get(key) instead of dict[key]?

后端 未结 10 2522
生来不讨喜
生来不讨喜 2020-11-21 05:51

Today, I came across the dict method get which, given a key in the dictionary, returns the associated value.

For what purpose is this funct

10条回答
  •  面向向阳花
    2020-11-21 06:11

    I will give a practical example in scraping web data using python, a lot of the times you will get keys with no values, in those cases you will get errors if you use dictionary['key'], whereas dictionary.get('key', 'return_otherwise') has no problems.

    Similarly, I would use ''.join(list) as opposed to list[0] if you try to capture a single value from a list.

    hope it helps.

    [Edit] Here is a practical example:

    Say, you are calling an API, which returns a JOSN file you need to parse. The first JSON looks like following:

    {"bids":{"id":16210506,"submitdate":"2011-10-16 15:53:25","submitdate_f":"10\/16\/2011 at 21:53 CEST","submitdate_f2":"p\u0159ed 2 lety","submitdate_ts":1318794805,"users_id":"2674360","project_id":"1250499"}}
    

    The second JOSN is like this:

    {"bids":{"id":16210506,"submitdate":"2011-10-16 15:53:25","submitdate_f":"10\/16\/2011 at 21:53 CEST","submitdate_f2":"p\u0159ed 2 lety","users_id":"2674360","project_id":"1250499"}}
    

    Note that the second JSON is missing the "submitdate_ts" key, which is pretty normal in any data structure.

    So when you try to access the value of that key in a loop, can you call it with the following:

    for item in API_call:
        submitdate_ts = item["bids"]["submitdate_ts"]
    

    You could, but it will give you a traceback error for the second JSON line, because the key simply doesn't exist.

    The appropriate way of coding this, could be the following:

    for item in API_call:
        submitdate_ts = item.get("bids", {'x': None}).get("submitdate_ts")
    

    {'x': None} is there to avoid the second level getting an error. Of course you can build in more fault tolerance into the code if you are doing scraping. Like first specifying a if condition

提交回复
热议问题