📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
1. Introduction
In Python, dictionaries are used to store data in key-value pairs. Unlike lists, dictionaries don't have an append method. However, adding new elements or appending to existing elements in a dictionary is a common task, which can be achieved using different methods.
Appending to a dictionary typically means adding a new key-value pair or updating the value associated with an existing key. If the value is a list, appending may mean adding a new item to the list.
2. Program Steps
1. Start with an existing dictionary.
2. Determine the key where the value should be appended or updated.
3. Check if the key exists and if its value is a list; then append to it. Otherwise, update or add the key-value pair.
4. Output the updated dictionary.
3. Code Program
# Initialize a dictionary with a list as a value my_dict = {'numbers': [1, 2, 3], 'letters': ['a', 'b']} # Append to the list under the 'numbers' key my_dict['numbers'].append(4) # Append a new key-value pair my_dict['colors'] = ['red'] # Check if the 'letters' key exists and append, else create a new list if 'letters' in my_dict: my_dict['letters'].append('c') else: my_dict['letters'] = ['c'] # Print the updated dictionary print(f"Updated dictionary: {my_dict}")
Output:
Updated dictionary: {'numbers': [1, 2, 3, 4], 'letters': ['a', 'b', 'c'], 'colors': ['red']}
Explanation:
1. my_dict is initialized with two keys: 'numbers' and 'letters', each with a list as its value.
2. .append(4) is called on the list associated with the 'numbers' key to add a new element.
3. A new key 'colors' with a list ['red'] as its value is added to my_dict.
4. An if statement checks if the key 'letters' exists. Since it does, .append('c') is called on its list.
5. print outputs my_dict, showing the appended values and the newly added key-value pair.
Comments
Post a Comment
Leave Comment