๐ Python Dictionary Methods โ Complete Guide
Python dictionaries are flexible key-value stores. Mastering dict methods unlocks faster, more readable data manipulation code.
Use dict.get() instead of dict[key] whenever the key might not exist โ it's crash-proof.
๐ป Code Example:
# Create and access user = {'name': 'santoshtvk', 'platform': 'pynfinity', 'premium': True} print(user['name']) # santoshtvk print(user.get('score', 0)) # 0 (default if key missing โ no KeyError) # Add / update user['score'] = 95 user.update({'city': 'Bangalore', 'platform': 'Pynfinity'}) # Delete del user['city'] score = user.pop('score', None) # Removes and returns; None if missing print(score) # 95 # Iterate for key, value in user.items(): print(f"{key}: {value}") # Merge (Python 3.9+) defaults = {'theme': 'dark', 'lang': 'Python'} settings = {'theme': 'light'} | defaults # user settings override defaults print(settings) # Dict comprehension courses = ['Python', 'AI', 'DevOps'] course_ids = {course: idx for idx, course in enumerate(courses, 1)} print(course_ids) # {'Python': 1, 'AI': 2, 'DevOps': 3} # Check keys if 'premium' in user: print("Premium user detected!")
| Concept | Key Takeaway |
|---|---|
| .get(key, default) | Safe access with fallback value |
| .items() | Iterate as (key, value) pairs |
| .keys() / .values() | Get all keys or all values as a view |
| .pop(key, default) | Remove and return value safely |
| .setdefault(key, value) | Set value only if key doesn't exist |
| {} | other_dict | Python 3.9+ clean dict merge |
Keep exploring and happy coding! ๐