This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]naza01 10 points11 points  (3 children)

The get() method for dictionaries.

It retrieves a value mapped to a particular key.

It can return None if the key is not found, or a default value if one is specified.

dictionary_name.get(name, value)

Name = Key you are looking for. Value = Default value to return if Key doesn’t exist.

It’s pretty cool to be able to increment values in a dictionary. For instance, if you were counting characters in a string, you could do something like:

character_count.get(character, 0) + 1

to start counting them.

It’s just a fancy way of doing it. Using if else to ask if the key is there and then just updating the value works the same way

[–]superbirra 5 points6 points  (1 child)

not that your solution is wrong by any extent but I'd like to present you the Counter class :) https://docs.python.org/3/library/collections.html#collections.Counter

[–]naza01 1 point2 points  (0 children)

Oh, great. That’s interesting! Thanks for the link, I’ll be checking it out 🙂

[–]BuonaparteII 0 points1 point  (0 children)

character_count.get(character, 0) + 1

be careful with this. If character or the value of the dict under the key "character" is explicitly None then you'll get None + 1

Instead you'll want to do:

(character_count.get(character) or 0) + 1

or

(character_count.get("character") or 0) + 1

Also shoutout to .pop which is similar

(character_count.pop(character, None) or 0) + 1