Get the value in dict so it works

Tram Ho

Opening

When working with dictionary in Python, there are many ways to look up the value of the “key” in the dictionary as well as assign the default value if the “key” does not already exist.

For example, I have a dict of person = {“name”: “BeautyOnCode”, “age”: 28}

Here are the ways I used to get the value of an existing key:

With a key that does not exist, if you use dict [key], you will get an error KeyError: 'class' Then, you can use the following ways to assign a value to a key that does not exist as follows:

Or catch an error like this:

If you are like me, have done as above, then this is the post for you, because there are more interesting ways, more concise than the ones above, you may not know so let’s read on ^^


There are two methods that involve assigning default values ​​to an existing key, dict.get (key [, value]) and dict.setdefault (key, value) .

The two friends are quite cool and are considered best practice in getting the value and assign default value to dict.

I will carefully introduce the syntax, usage and compare the two with each other.

Body post

dict.get (key [, value])

The get () function returns the value of “key” if the keyword is in dict. Syntax: dict.get (key [, value])

This function accepts up to two variables:

  • key is the keyword to look for in dict
  • ** value (** optional – this field is optional): is the value to return if “key” is not found in the dict. If not assigned, None is returned by default

For example:

alt

In the above example:

The key “name” exists in the dict person so the result is its value “BeautyOnCode”

The key “class” does not exist in the dict, and there is no assigned default so person.get (“class”) is None is True.

Key “class” does not exist in dict, and I assign the default value of 12 so it returns the default value of 12.

Best practice : Using dict.get (key, default) when getting a value in dict and returning a default or returning None can avoid writing long code handling KeyErrror or having to check if the key exists in the dict. like the example at the beginning of the post.

dict.setdefault (key, value)

The setdefault () function returns the value of “key” if the keyword is in dict. If the keyword “key” is not already in the dict, dict will be appended with this keyword with “value” passed. Syntax: dict.setdefaut (key [, value])

This function accepts up to two variables:

  • key is the keyword to look for in dict
  • value (optional – this field is optional): “key” with value “value” will be assigned to dict if “key” is not found in dict. If there is no “value”, the default value is None.

Note : If the value of the key is already there, the default value will no longer be assigned

For example:

In the above example:

Key “class” does not exist yet, so the default value for her is None, because there is no default value passed.

Key “class” already exists with the value “None” so this time setdefault is no longer accepted.

So this function only works when the key does not exist.

Best practice : Using dict.setdefault (key, value) when initializing dict can avoid setting default values ​​with if … else.

For example:

Instead of writing:

Now I write

Do you think it’s cooler?

Have you seen the two different nuns? I think you guessed it, let’s check it out!

Compare

Similarities

When working with keys that do not exist in dictionary, these two functions return the default value they want to return.

The example below shows both ways to return the value b as ‘Bar’.

Differences

However, the difference here is:

The .setdefault () function adds the default value with the keyword to the dict, and is only assigned the first time (when the key doesn’t exist).

Therefore, the .setdefault () function will correspond to this code:

The .get (key, value) function won’t add a value for that key to the dict, only returns the expected default results.

And the .get (key, value) function will correspond to this code:

Here is the output dict a of the above example:

End

The post here is temporary, learning how to do Pythonista is not so difficult, everyone, I just need to pay attention to be able to improve from this small code.

Thank you for reading! I’m practicing blogging, everyone visit my house to play. Follow / like this fanpage to update the latest posts. Some good sources that I can collect are also saved on here

BeautyOnCode

Share the news now

Source : Viblo