3 min read•june 24, 2024
Python allow for complex data organization, enabling hierarchical structures like employee records or product catalogs. They're created by dictionaries within other dictionaries, accessed using key sequences, and can be modified or retrieved with various methods.
offers a concise way to create dictionaries from existing iterables. This efficient technique allows for filtering and transforming data in a single line, making it a powerful tool for dictionary creation and manipulation in Python programming.
employee_info = { 'John': { 'department': 'Sales', 'salary': 50000 }, 'Emily': { 'department': 'Marketing', 'salary': 60000 } }
dictionary[outer_key][inner_key]
employee_info['John']['department']
retrieves John's department (Sales)employee_info['Emily']['salary'] = 65000
updates Emily's salary[get()](https://www.fiveableKeyTerm:get())
method to provide a default value if a key is missing and avoid [KeyError](https://www.fiveableKeyTerm:KeyError)
employee_info.get('Michael', {}).get('salary', 0)
returns 0 if 'Michael' or 'salary' key doesn't existstudent_grades['Alice']['Math'] = 90
updates Alice's Math gradeKeyError
if 'John' in employee_info and 'department' in employee_info['John']: department = employee_info['John']['department']
get()
method to provide a default value if a key is missing
product_price = product_catalog.get('books', {}).get('fiction', 0)
returns 0 if 'books' or 'fiction' key doesn't exist{key_expr: value_expr for item in iterable if condition}
key_expr
determines the keys, value_expr
determines the valuesitem
represents each element in the iterable
condition
filters items to includenames = ['Alice', 'Bob', 'Charlie'] name_lengths = {name: len(name) for name in names} # name_lengths = {'Alice': 5, 'Bob': 3, 'Charlie': 7}
subjects = ['Math', 'Science', 'English'] student_scores = {student: {subject: 0 for subject in subjects} for student in ['John', 'Emily']}
numbers = [1, 2, 3, 4, 5] even_squares = {x: x**2 for x in numbers if x % 2 == 0} # even_squares = {2: 4, 4: 16}