3 min read•june 24, 2024
Dictionaries Python offer powerful tools data manipulation. Conditional checks and looping techniques allow you to search, filter, and process contents efficiently. These methods are essential for working with complex data structures in real-world programming scenarios.
Advanced operations take your skills further. Dictionary comprehensions and enable you to create and modify dictionaries based on specific conditions. These techniques streamline your code and enhance your ability to work with structured data.
in
keyword
[True](https://www.fiveableKeyTerm:TRUE)
if the key is found, [False](https://www.fiveableKeyTerm:FALSE)
otherwiseif 'name' in student_info:
[values()](https://www.fiveableKeyTerm:values())
view
values()
returns a view object containing all the values in the dictionaryif 'John' in student_info.values():
[get()](https://www.fiveableKeyTerm:get())
method to retrieve the value associated with a key, providing a default value if the key is not found
dictionary.get(key, default_value)
age = student_info.get('age', 18)
result = 'Adult' if age >= 18 else 'Minor'
for
loop
for name in phone_book: print(name, phone_book[name])
values()
method
values()
returns a view object containing all the values in the dictionaryfor phone_number in phone_book.values(): print(phone_number)
[items()](https://www.fiveableKeyTerm:items())
method
items()
returns a view object containing tuples of key-value pairsfor
loop to access both the key and valuefor name, phone_number in phone_book.items(): print(name, phone_number)
for department, employees in company.items(): for employee, details in employees.items(): print(f"{employee} works in {department}")
[keys()](https://www.fiveableKeyTerm:keys())
method to get a view of all keys in the dictionary
if 'address' in student_info.keys():
values()
method to get a view of all values in the dictionary
for grade in student_grades.values(): if grade >= 90: print("A")
items()
method to get a view of all key-value pairs as tuples
for item, price in store_inventory.items(): if price > 100: print(item, "is expensive")
for name, score in exam_scores.items(): if score < 60: print(name, "failed the exam")
squared_numbers = {x: x**2 for x in range(10) if x % 2 == 0}
valid_entries = {k: v for k, v in data.items() if v is not None and v != ''}
grade_status = {name: 'Pass' if score >= 60 else 'Fail' for name, score in exam_scores.items()}