|
| 1 | +""" |
| 2 | +Basic dictionary operations in Python. |
| 3 | +
|
| 4 | +This module demonstrates fundamental dictionary operations including: |
| 5 | +- Creating dictionaries |
| 6 | +- Accessing and modifying elements |
| 7 | +- Different methods for removing elements |
| 8 | +- Common dictionary operations and methods |
| 9 | +""" |
| 10 | + |
| 11 | +# Examples of dictionary operations |
| 12 | + |
| 13 | +# Creating a dictionary |
| 14 | +fruits = {"apple": 100, "banana": 200, "orange": 150} |
| 15 | + |
| 16 | +# Accessing elements |
| 17 | +print(fruits["apple"]) # Output: 100 |
| 18 | + |
| 19 | +# Adding/Updating elements |
| 20 | +fruits["grape"] = 300 # Adding new element |
| 21 | +fruits["apple"] = 120 # Updating existing element |
| 22 | +# fruits is now: {"apple": 120, "banana": 200, "orange": 150, "grape": 300} |
| 23 | + |
| 24 | +# Methods for removing elements |
| 25 | +# 1. Using del statement |
| 26 | +del fruits["banana"] |
| 27 | +# fruits is now: {"apple": 120, "orange": 150, "grape": 300} |
| 28 | + |
| 29 | +# 2. Using pop() method - returns the removed value |
| 30 | +price = fruits.pop("orange") # price = 150 |
| 31 | +# fruits is now: {"apple": 120, "grape": 300} |
| 32 | + |
| 33 | +# 3. Using popitem() method - removes and returns random item (last item in Python 3.7+) |
| 34 | +last_item = fruits.popitem() # last_item = ("grape", 300) |
| 35 | +# fruits is now: {"apple": 120} |
| 36 | + |
| 37 | +# 4. Using clear() method - removes all elements |
| 38 | +fruits.clear() |
| 39 | +# fruits is now: {} |
| 40 | + |
| 41 | +# Dictionary operations |
| 42 | +sample_dict = {"name": "Tanaka", "age": 25, "city": "Tokyo"} |
| 43 | + |
| 44 | +# Checking if key exists |
| 45 | +if "name" in sample_dict: |
| 46 | + print("Key 'name' exists") # Will be printed |
| 47 | + |
| 48 | +# Getting list of keys |
| 49 | +keys = sample_dict.keys() # dict_keys(['name', 'age', 'city']) |
| 50 | + |
| 51 | +# Getting list of values |
| 52 | +values = sample_dict.values() # dict_values(['Tanaka', 25, 'Tokyo']) |
| 53 | + |
| 54 | +# Getting key-value pairs |
| 55 | +items = ( |
| 56 | + sample_dict.items() |
| 57 | +) # dict_items([('name', 'Tanaka'), ('age', 25), ('city', 'Tokyo')]) |
| 58 | + |
| 59 | +# Getting value with default |
| 60 | +score = sample_dict.get("score", 0) # Returns 0 if key doesn't exist |
0 commit comments