Appending to list in Python dictionary
In this article, we are going to see how to append to a list in a Python dictionary.
Method 1: Using += sign on a key with an empty value
In this method, we will use the += operator to append a list into the dictionary, for this we will take a dictionary and then add elements as a list into the dictionary.
Python3
Details = { "Destination" : "China" , "Nstionality" : "Italian" , "Age" : []} Details[ "Age" ] + = [ 20 , "Twenty" ] print (Details) |
Output:
{'Destination': 'China', 'Nstionality': 'Italian', 'Age': [20, 'Twenty']}
You can as well append one item.
Method 2: Using if statement
In this method, we will use conditions for checking the key and then append the list into the dictionary.
Python3
Details = {} Details[ "Age" ] = [ 20 ] print (Details) if "Age" in Details: Details[ "Age" ].append( "Twenty" ) print (Details) |
Output:
{'Age': [20]} {'Age': [20, 'Twenty']}
Method 3: Using defaultdict() method
In this method, we are using defaultdict() function, It is a part of the collections module. You have to import the function from the collections module to use it in your program. and then use to append the list into the dictionary.
Python3
from collections import defaultdict Details = defaultdict( list ) Details[ "Country" ].append( "India" ) print (Details) |
Output:
defaultdict(<class 'list'>, {'Country': ['India']})
Since append takes only one parameter, to insert another parameter, repeat the append method.
Python3
from collections import defaultdict Details = defaultdict( list ) Details[ "Country" ].append( "India" ) Details[ "Country" ].append( "Pakistan" ) print (Details) |
Output:
defaultdict(<class 'list'>, {'Country': ['India', 'Pakistan']})
Method 4: Using update() function
We will use the update function to add a new list into the dictionary. You can use the update() function to embed a dictionary inside another dictionary.
Python3
Details = {} Details[ "Age" ] = [] Details.update({ "Age" : [ 18 , 20 , 25 , 29 , 30 ]}) print (Details) |
Output:
{'Age': [18, 20, 25, 29, 30]}
Method 5: Adding a list directly to a dictionary
You can convert a list into a value for a key in a python dictionary using dict() function.
Python3
Values = [ 18 , 20 , 25 , 29 , 30 ] Details = dict ({ "Age" : Values}) print (Details) |
Output:
{'Age': [18, 20, 25, 29, 30]}