Unlock the Power of Python Dictionaries
A Python dictionary is a versatile collection of key-value pairs, offering a unique way to store and manage data. Unlike lists and tuples, dictionaries allow you to associate a value with a specific key, making it easy to access and manipulate data.
Crafting a Dictionary
To create a dictionary, simply place key-value pairs inside curly brackets {}
, separated by commas. For instance:
country_capitals = {'Germany': 'Berlin', 'France': 'Paris', 'Italy': 'Rome'}
This dictionary contains three elements, where ‘Germany’ is the key and ‘Berlin’ is the corresponding value.
Important Notes
When working with dictionaries, keep in mind that:
- Dictionary keys must be immutable, such as tuples, strings, or integers. Avoid using mutable objects like lists as keys.
- You can also create a dictionary using the built-in
dict()
function. - Immutable objects, like integers, tuples, and strings, cannot be changed once created.
- Dictionary values can be of any data type, including mutable types like lists.
- Keys in a dictionary must be unique. If duplicates occur, the last value will overwrite the previous one.
Accessing Dictionary Items
To retrieve a value from a dictionary, simply place the key inside square brackets. For example:
print(country_capitals['Germany']) # Output: Berlin
Alternatively, you can use the get()
method to access dictionary items.
Adding Items to a Dictionary
Expanding your dictionary is easy! Assign a value to a new key, like this:
country_capitals['Spain'] = 'Madrid'
Removing Dictionary Items
Use the del
statement to remove an element from a dictionary:
del country_capitals['Italy']
Alternatively, you can use the pop()
method to remove an item, or the clear()
method to remove all items at once.
Changing Dictionary Items
Python dictionaries are mutable, so you can change the value of a dictionary element by referring to its key:
country_capitals['France'] = 'Lyon'
You can also use the update()
method to add or change dictionary items.
Iterating Through a Dictionary
Since Python 3.7, dictionaries maintain the order of their items. Use a for
loop to iterate through dictionary keys one by one:
for country in country_capitals: print(country)
Finding Dictionary Length
Get the length of a dictionary using the len()
function:
print(len(country_capitals))
Python Dictionary Methods
Discover the various methods available for working with dictionaries, including:
get()
: Access dictionary itemspop()
: Remove an item from a dictionaryclear()
: Remove all items from a dictionaryupdate()
: Add or change dictionary itemskeys()
: Return a list of dictionary keysvalues()
: Return a list of dictionary valuesitems()
: Return a list of dictionary key-value pairs
Dictionary Membership Test
Use the in
and not in
operators to check whether a key exists in a dictionary:
print('Germany' in country_capitals) # Output: True
Remember, the in
operator checks for key existence, not value existence.