Zoran Pandovski
By Zoran Pandovski

Python dict.key vs dict[key]

Python dict.key vs dict[key]

To get the value from the dictionary the most pythonic way would be to use the square brackets [ ] e.g

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# note that dict keys are case-sensitive

capitals = {

    'usa' : 'washinghton',

    'england' : 'london',

    'france' : 'paris'

}

capitals['usa']

>>>'washinghton'

Also, you can use the get method e.g

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
capitals = {

    'usa' : 'washinghton',

    'england' : 'london',

    'france' : 'paris'

}

capitals.get('usa')

>>>'washinghton'

So, in both examples we got the same response ‘washinghton’. The question now is what is the difference between this two examples? Let’s try

another example, using the key that isn’t in the capitals dict:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
capitals = {

    'usa' : 'washinghton',

    'england' : 'london',

    'france' : 'paris'

}

capitals['spain']

>>> KeyError: 'spain'

We got the KeyError, which is quite expected because we know that the ‘spain’ key is not avaiable in the dictionary. Let’s try with get method now:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
capitals = {

    'usa' : 'washinghton',

    'england' : 'london',

    'france' : 'paris'

}

capitals.get('germany')

>>>

We didn’t get any Error back, just the empty value. That is the difference between using get method and square brackets. The dict[key] will always throw KeyError when the key is not found. The get method accepts additonal parameter dict.get(key, [default]) which returnes the default value in case the key is not found. In our case we didn’t specify value so it was setup as None.