After building our relational database, the next step is querying the database to retrieve the data we need. The main interaction for end users or software apps is the ability to get that data in a meaningful way from the database. This is similar to the SQL's SELECT statement. In the context of our simple example using a Python dictionary as our database, we can achieve this by accessing the key-value pairs with specific keys.
Suppose we have a simple database with keys 'mathematics' and 'computer_science', each having its related data. We can create a read(database, key)
function to query the database. The function takes the 'database' (our Python dictionary) and a 'key' as parameters and then checks if the key exists in the database. If it does, it returns the associated value. If it doesn't, it returns a message indicating that no data was found for the provided key.
With this method, we can easily retrieve expenses related to 'mathematics', like under the topic categories ('calculus', 'combinatorics', 'algebra'), its difficulty level as 'hard', and a boolean indicating if it is fun. Similarly, for 'computer_science', we get related topics ('data_structure', 'algorithms', 'operating_systems'), difficulty level as 'medium', and a boolean indicating fun as well. A search for 'finance' returns 'No data found for key: finance' as there is no data associated with 'finance' in our database.
This is a simple interpretation of querying a database, and in real-world applications, substantial and complex queries can be made using actual SQL or other database query languages.
xxxxxxxxxx
if __name__ == "__main__":
# Python logic here
database = {
'mathematics': {
'topics': ['calculus', 'combinatorics', 'algebra'],
'difficulty': 'hard',
'is_fun': True
},
'computer_science': {
'topics': ['data_structure', 'algorithms', 'operating_systems'],
'difficulty': 'medium',
'is_fun': True
}
}
# Querying the database
def read(database, key):
if key in database:
return database[key]
else:
return 'No data found for key: {}'.format(key)
print(read(database, 'computer_science'))
print(read(database, 'mathematics'))
print(read(database, 'finance'))