Dictionaries are a fundamental data structure in Python that allows you to store and manipulate collections of key/value pairs effectively. Unlike lists, which are ordered and indexed by numbers, dictionaries provide a way to map arbitrary keys to their corresponding values.
Creating a Dictionary
To create a dictionary, you can use curly braces {}
and separate each key/value pair with a colon :
. Here’s an example with a single key/value pair:
dog = { 'name': 'Roger' }
In this example, the key is 'name'
, and the corresponding value is 'Roger'
.
Accessing and Modifying Values
You can access the values in a dictionary by using the key inside square brackets. For example:
dog['name'] # Output: 'Roger'
You can also modify the value associated with a specific key by assigning a new value to it:
dog['name'] = 'Syd'
Additional Dictionary Operations
Apart from accessing and modifying values, dictionaries offer several other useful methods and operations:
get()
Method
The get()
method allows you to retrieve the value of a key while providing a default value if the key doesn’t exist:
dog.get('name') # Output: 'Roger'
dog.get('test', 'default') # Output: 'default'
pop()
Method
The pop()
method retrieves the value of a key and removes the key/value pair from the dictionary:
dog.pop('name') # Output: 'Roger'
popitem()
Method
The popitem()
method retrieves and removes the last key/value pair inserted into the dictionary:
dog.popitem()
in
Operator
You can check if a key is present in a dictionary using the in
operator:
'name' in dog # Output: True
keys()
, values()
, and items()
Methods
These methods allow you to retrieve the keys, values, and key/value pairs of a dictionary, respectively:
list(dog.keys()) # Output: ['name', 'age']
list(dog.values()) # Output: ['Roger', 8]
list(dog.items()) # Output: [('name', 'Roger'), ('age', 8)]
len()
Function
The len()
function can be used to get the number of key/value pairs in a dictionary:
len(dog) # Output: 2
Adding and Removing Key/Value Pairs
You can add a new key/value pair to a dictionary by assigning a value to a new key:
dog['favorite food'] = 'Meat'
To remove a specific key/value pair from a dictionary, you can use the del
statement:
del dog['favorite food']
Copying a Dictionary
To create a copy of a dictionary, you can use the copy()
method:
dogCopy = dog.copy()
Conclusion
Dictionaries are a powerful data structure in Python that allow you to store and manipulate key/value pairs efficiently. Understanding how to create, access, and modify dictionaries, as well as the various methods available, can greatly enhance your Python programming skills.