Learning Python: Dictionaries
Another data structure in Python are dictionaries. Dictionaries allow us to create a collection composed of key/value pairs.
Examples
person = {'name': 'Peter'}
The key can be a string, a tuple or a number. The value can be anything.
person_age = {'name': 'Peter', age: 47}
We can access the values in the above dictionary like so:
person_age['name'] # 'Peter' person_age['age'] # 47
The get()
method can also be used to retrieve the value:
person_age.get('name') # 'Peter'
We can also change the value in the following manner:
person_age['name'] = 'Tom'
The pop()
method can be used to retrieve the value of a particular key and then delete the key/value pair that was just retrieved:
person_age.pop('name') # 'Tom'
The popitem()
method removes the last key/value pair in a dictionary:
person_age.popitem()
We can check if a key is in a dictionary:
'age' in person_age # True
We can create a list of keys that are in the person_age
dictionary using the keys()
method:
print(list(person_age.keys())) # ['age']
We can also create a list of values that are in the person_age
dictionary using the values()
method:
print(list(person_age.values())) # [47]
A list of key/value pairs of the person_age
dictionary can also be made using the items()
method:
person_city = {'name': 'Sally', 'city': 'Toronto'} print(list(person_city).items()) # [('name', 'Sally'), ('city', 'Toronto')]
We can get the length of a dictionary using the len()
method:
len(person_city) # 2
We can add a new key/value pair to the person_city
dictionary:
person_city['province'] = 'Ontario'
In order to delete a key/value pair, we use the del
statement:
del person_city['province']
We can also make a copy of the person_city
dictionary using the copy()
:
person_city_copy = person_city.copy()
This blog post was originally published on my blog Communicode, where I write about different tech topics.