Lesson · 40 min · Free
Python Dictionaries Essentials
Python Dictionaries Essentials body { font-family: sans-serif; line-height: 1.6; margin: 20px; } h1, h2 { color: #2c3e50; } pre { background-color: #ecf0f1; padding: 15px; border-radius: 5px; overflow-x: auto; } code { f
Python Dictionaries Essentials
In the realm of data handling, particularly within scientific computing and bioinformatics, Python dictionaries emerge as an indispensable data structure. Unlike lists, which store ordered collections of items accessed by an integer index, dictionaries store data in unordered key-value pairs. This allows for highly efficient retrieval and manipulation of data using descriptive keys, making them analogous to a physical dictionary or a lookup table where you find a definition (value) by looking up a word (key). For pharmacy and biotech students, this structure is particularly useful for managing experimental data, patient records, gene annotations, or drug properties, where each piece of information needs a unique, meaningful identifier. The fundamental characteristic of a dictionary is its mapping from immutable keys to mutable values. Keys must be unique and can be of any immutable type (strings, numbers, tuples). Values, on the other hand, can be of any data type, including other dictionaries, lists, or custom objects. This flexibility allows for the creation of complex, nested data structures that accurately represent intricate biological or chemical datasets.
Creating and Accessing Dictionaries
Creating a dictionary in Python is straightforward, using curly braces {} with key-value pairs separated by colons : , and each pair separated by a comma. Accessing values is done by referencing their corresponding key within square brackets, similar to how you would access elements in a list by index. Attempting to access a non-existent key will raise a KeyError , which can be handled using error handling techniques or by checking for key existence. # Example 1: Creating and Accessing a Dictionary for Drug Information # A dictionary to store information about a specific drug drug_info = { "name": "Atorvastatin", "class": "Statin", "target": "HMG-CoA reductase", "molecular_weight": 558.64, "indications": ["Hypercholesterolemia", "Cardiovascular disease prevention"], "side_effects": ["Myalgia", "Hepatotoxicity"], "half_life_hours": 14 } print("Drug Name:", drug_info["name"]) print("Drug Class:", drug_info["class"]) print("Molecular Weight:", drug_info["molecular_weight"]) # Accessing a list within the dictionary print("Indications:", drug_info["indications"]) print("First Indication:", drug_info["indications"][0]) # Attempting to access a non-existent key will cause an error # print(drug_info["dosage"]) # This would raise a KeyError # Safely checking for a key's existence before accessing if "dosage" in drug_info: print("Dosage:", drug_info["dosage"]) else: print("Dosage information not available for Atorvastatin.") # Using .get() method for safe access (returns None if key not found, or a default value) dosage = drug_info.get("dosage", "Not specified") print("Dosage (using .get()):", dosage) Dictionaries are dynamic; you can add new key-value pairs or modify existing ones after creation. This mutability is crucial for managing evolving datasets, such as updating experimental results or adding new findings to a gene annotation database. # Example 2: Modifying and Adding to a Dictionary for Gene Data # Initial dictionary for a gene gene_data = { "gene_id": "ENSG00000123456", "symbol": "TP53", "chromosome": "17", "start_position": 7661779, "end_position": 7687538, "function": "Tumor suppressor", "known_variants": ["R175H", "G245S"] } print("Original Gene Data:", gene_data) # Modifying an existing value gene_data["start_position"] = 7661778 print("Modified Start Position:", gene_data["start_position"]) # Adding a new key-value pair gene_data["expression_level"] = {"tissue_A": 150, "tissue_B": 230} print("Added Expression Level:", gene_data["expression_level"]) # Adding another variant to the list within the dictionary gene_data["known_variants"].append("R273H") print("Updated Known Variants:", gene_data["known_variants"]) # Removing a key-value pair using del del gene_data["end_position"] print("After deleting 'end_position':", gene_data) # Removing a key-value pair and getting its value using .pop() removed_function = gene_data.pop("function") print("Removed Function:", removed_function) print("Dictionary after pop():", gene_data)
Key Takeaways for Pharmacy/Biotech Students:
Descriptive Data Storage: Dictionaries allow you to store and retrieve data using meaningful labels (keys) instead of numerical indices, making your code more readable and data management more intuitive for complex biological or chemical entities. Efficient Lookups: Accessing values by key is highly optimized in Python, offering near-constant time performance, which is crucial for large datasets like genomic sequences or drug compound libraries. Flexible Data Structures: Values can be of any type, enabling the nesting of lists, other dictionaries, or custom objects to represent hierarchical or complex scientific data (e.g., a dictionary for a gene containing a list of variants, or a dictionary for a patient containing another dictionary for lab results). Dynamic Data Management: Dictionaries can be easily modified by adding, updating, or deleting key-value pairs, accommodating the iterative nature of scientific research and data acquisition. Error Prevention: Understanding KeyError and using methods like .get() or the in operator is vital for robust code that handles cases where expected data might be missing.
Practice Exercise: Patient Record Management
You are tasked with creating a simplified patient record system for a clinical trial. Create a Python dictionary named patient_record for a hypothetical patient. Include the following key-value pairs: "patient_id" : "PNT001" (string) "age" : 62 (integer) "gender" : "Female" (string) "diagnoses" : ["Type 2 Diabetes", "Hypertension"] (list of strings) "medications" : {"Metformin": "500mg BID", "Lisinopril": "10mg QD"} (a nested dictionary where keys are drug names and values are dosages) "visit_dates" : ("2023-01-15", "2023-03-20") (a tuple of strings) After creating the dictionary, perform the following operations: Print the patient's ID and age. Add a new diagnosis "Peripheral Neuropathy" to the "diagnoses" list. Update the dosage of "Lisinopril" to "20mg QD". Add a new medication "Aspirin" with dosage "81mg QD" to the "medications" dictionary. Attempt to retrieve the patient's blood type using .get() , providing "Unknown" as a default value if the key is not present. Print the result. Finally, print the entire updated patient_record dictionary.
Watch the full lesson — free
This topic is part of Python Programming - Basics, a complete AI-narrated video course. Press play once and watch the entire lecture like a movie.
Start the course free →