0

I know d[key] will take the 'd' items and return them as keys, but if I only use d[key] I always get a keyerror. I've only seen it been used with .get(). For example I saw another question on here that I copied to study from:

myline = "Hello I'm Charles"

character = {}

for characters in myline:
    character[characters] = character.get(characters, 0) + 1

print character 

If you can use d[key] alone, could you give me some examples? Why wouldn't the above code work if I remove "character.get(characters, 0) + 1"?

Amon
  • 2,725
  • 5
  • 30
  • 52

3 Answers3

1

The KeyError is raised only if the key is not present in the dict.

dict.get is interpreted as:

>>> print dict.get.__doc__
D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.

In your particular example, you're trying to calculate count of each character. As the dict is initially empty, so you need to set the key first before trying to fetch it's value and then add 1 to it.

So, character[characters] = character.get(characters, 0) + 1 can also be written as:

if characters in character:     #if key is present in dict
   character[characters] += 1
else:
   character[characters] = 0   #if key is not present in dict, then set the key first
   character[characters] += 1

So, you can see dict.get saves these steps, by returning the value of key if the key is present else return the default value 0.

But, for this example collections.Counter is the best tool.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • So basically the reason that this won't return a KeyError is because you're telling the program to return '0' if the Key is not present in the dictionary? – Amon Aug 13 '13 at 06:21
  • So is there every a time where you would use d[key] on its own? As opposed to setting it equal to something like we did here? I'd like to see this used in a different context. – Amon Aug 13 '13 at 06:41
  • @Amon If you're sure about the dict keys then always use `d[key]`, it is much faster than `dict.get`. For example iteration over a dict. – Ashwini Chaudhary Aug 13 '13 at 07:03
0

dict.get(a,b) means if key a is not in dict, will return value b, else return the value of key a.

While d[key] get the value of key, but if key is not in dict it will raise a keyerror

David.Zheng
  • 903
  • 8
  • 6
0

The d.get(key, default) is the public accessor for a dictionary - it provides a mechanism for key missing.

Steve Barnes
  • 27,618
  • 6
  • 63
  • 73