The Power of Dictionaries:
- While lists organize their elements by position, dictionaries organize information by association.
- For example, when you use a dictionary to look up the definition of “sentient,” you don’t start at page 1 (or 0) — instead you turn directly to the words beginning with “S.”
What are Dictionaries:
- In Python, a dictionary is a set of keys with data values. More precisely, a Python dictionary is a collection of key-value pairs. Each key is connected to a value, and you can use a key to access the value associated with that key.
- A key’s value can be a number, a string, a list or even another dictionary.
- For example, the keys in Webster’s Dictionary comprise the set of words, whereas the associated data values are their definitions.
A Simple Dictionary:
- A dictionary is wrapped in braces {} with a series of key-value pairs inside the braces. Here is an example:
python
1person = {
2'firstName': 'michael',
3'lastName': 'burnham',
4'age': 35,
5'gender': 'female',
6}
7
8print(person['firstName'])
9print(person['lastName'])
10print(person['age'])
11print(person['gender'])Output:
1michael
2burnham
335
4female- The dictionary person stores the person’s first name, last name, age and gender.
- Python has returned values associated with their keys.
- Every key is connected to its value by a colon, and individual key-value pairs are separated by commas.
Adding New Key-Value Pairs:
python
1
2person = {
3'firstName': 'michael',
4'lastName': 'burnham',
5'age': 35,
6'gender': 'female',
7}
8
9print(person)
10
11person['occupation'] = 'scientist'
12print(person)Output:
1{'firstName': 'michael', 'lastName': 'burnham', 'age': 35, 'gender': 'female'}
2{'firstName': 'michael', 'lastName': 'burnham', 'age': 35, 'gender': 'female', 'occupation': 'scientist'}- Note the final version of the dictionary contains five key-value pairs, versus four.