Python Dictionaries

To create a dictionary in python:

1
myDict = {'Name':'John', 'Age':32, 24:'Python', 34:23......etc }

The key is to the left of the colon, the value to the Right. Dictionaries are mutable and can hold any objects. Keys have to be of an immutable type.

To access the values within the dictionary you have to use the respective key.

1
myDict['Age']

will return 32 from the example above.

1
myDict[34]

will return 23

If you request a key that isn’t in the dictionary you will return an error. Therefore it is a good idea to use the .get method.

1
myDict.get('Name')

will return ‘John’

1
myDict.get(54)

will return Null instead of an error.

You can also add a default return value

1
myDict.get(key, default=None)

default – This is the Value to be returned in case key does not exist.

^