Appending into a List in Python Dictionary

Hello developers, In this article we will discuss about appending into a List in Dictionary in Python. Before diving into the topic, lets first discuss what is a Dictionary is in Python. We know, data structures refer to specialized formats, used for organizing, storing, processing, and easy retrieving of data and data efficiently in memory. They provide structures or frameworks for arranging data to meet specific objectives and data manipulation. Similarly in python, Dictionaries are powerful data structures that allow you to store and retrieve data using key-value pairs, whereas a list is a mutable and versatile data structure used to store a collection of elements and it is defined by enclosing comma-separated values within square brackets [ ].

Creation and appending into a dictionary

So, to create a dictionary we can write the following code:

#creation of a dictionary
d = {'name': 'Adam', 'age': 15, 'city': 'New York'}

Now that we have created a dictionary with some values, lets see how to append value in that dictionary in the following code:

# Adding elements to an existing dictionary
d['country'] = 'USA'

Here what we did was to add new key-value pairs to a dictionary using assignment (d['country'] = 'USA')

So, now that we know about a dictionary, lets add a list with the code given below:

d = {'name': 'Adam', 'age': 15, 'city': 'Delhi'}
print("Original:", d)
 
# appending the list
d.update({"Shopping_list": ["apple", "Milk","Banana"]})
print("Modified:", d)

The above code will give the following output:

Original: {'name': 'Adam', 'age': 15, 'city': 'Delhi'}
Modified: {'name': 'Adam', 'age': 15, 'city': 'Delhi', 'Shopping_list': ['apple', 'Milk', 'Banana']}

So, by this way we can easily add a list in our python code, just by using the update function.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top