A dictionary is a collection that stores data in key/value pairs and is equivalent to a java map. Keys can be of any immutable type.
Create
items = dict()
# or
items = {}
items['apple'] = 12
items['grape'] = 5
items['orange'] = 7
print(items)
{'apple': 12, 'grape': 5, 'orange': 7}
print(items['apple'])
12
otherItems = {'apple': 10, 'grape': 15, 'orange': 47}
Inspect
We can use the in operator to check if a key already exists
if 'apple' in items:
# do something if apple exists
Retrieving Values
Retrieving a value for a key not contained in the dictionary will throw an error. The dictionary get method returns a default value if the key is not contained in the dictionary.
x = items.get('carrot', 0)
Methods
- items(): returns a list of key/value tuples
- keys(): returns a list of keys
- values(): returns a list of values
Functions
- list(dictionary): returns a list of keys
Iteration
To iterate through a dictionary use the items method to obtain a list of tuples and iterate through the list using a for loop with two iteration variables:
for k, v in dictionary.items():
print(k, v)