Python dict append to key

Python Dictionary Append: How to add key-value pair

In this Python tutorial, we will learn about the Python dictionary append. Here appending to Python Dictionary means adding new key-value pair to a Python Dictionary.

In Python, we can append data into the Python DIctionary using the following 6 methods.

  1. Using append() method
  2. Using dict.update() method
  3. Using extend() method
  4. Using for loop
  5. Using square brackets
  6. Using dictionary comprehension
  7. Using dict() constructor

Python Dictionary Append

Here, the basic meaning of the Pyhton Dictionary Append is to add new key-value pair to an existing Python Dictionary.

And we can easily append a key-value pair into a dictionary in Python using multiple methods. So, let us start with the first method:

Method 1: Python Dictionary Append using dict() constructor

In Python, we can also define a dictionary and its objects using the dict() constructor. Moreover, we can use the same dict() function on an existing dictionary to add more key-value pairs to the dictionary.

Читайте также:  Java set selenium chrome driver

Here is an example of the implementation.

# Defining a dictionary in Python countries_hdi = < 'Canada': 0.937, 'United Kingdom': 0.935, 'United States': 0.921, >print("Original Dictionary:", countries_hdi) # Using dict() to append data countries_hdi = dict(countries_hdi, Australia=0.941) print("Dictionary after adding data:", countries_hdi)

In the example, we append the ley-value pair to the countries_hdi dictionary.

So, after executing the above Python program, we will get the following result.

Original Dictionary: Dictionary after adding data: 'Australia': 0.941>

So, in this section, we understood how to add key-value pairs to the dictionary using dict() constructor in Python.

Method 2: Python Dictionary Append using dictionary comprehension

With this method, we will understand how to use the unpacking operator (**) with dictionary comprehension to append new key-value pair to an existing dictionary.

The Python code for this execution is given below.

# Defining a dictionary in Python countries_hdi = < 'Canada': 0.937, 'United Kingdom': 0.935, 'United States': 0.921, >print("Original Dictionary:", countries_hdi) # Using dict comprehension to append data countries_hdi = <**countries_hdi, **<'Switzerland': 0.962>> print("Dictionary after adding data:", countries_hdi)

Here we used the unpacking operator with dictionary comprehension to append key-value pair to countries_hdi dictionary.

Once we run the above Python program, we will get the following result.

Original Dictionary: Dictionary after adding data: 'Switzerland': 0.962>

So, in this section, we understood how to add key-value pairs to the dictionary using dictionary comprehension and the unpacking operator (**) in Python.

Method 3: Python Dictionary Append using square brackets

One of the simplest methods to append or add new key-value pair to an existing Python Dictionary is by using the square brackets.

Basically, the square brackets are used with a dictionary to fetch the value of an existing key. However, if a particular key does not exist, it will add automatically.

# Defining a dictionary in Python countries_hdi = < 'Canada': 0.937, 'United Kingdom': 0.935, 'United States': 0.921, >print("Original Dictionary:", countries_hdi) # Using square brackets to append key-value pair countries_hdi['Australia'] = 0.941 countries_hdi['Switzerland'] = 0.962 print("Dictionary after adding data:", countries_hdi)

In the above example, we are using square brackets to append new values for Australia and Switzerland keys.

The result of the above Python program is shown below.

Original Dictionary: Dictionary after adding data: 'Australia': 0.941, 'Switzerland': 0.962>

So, in this section, we understood how to add or append key-value pairs to the dictionary using square brackets in Python.

Method 4: Python Dictionary Append using for loop

Now, if we use square brackets, we need to specify each key-value pair manually. However, we can simplify this approach by creating a list containing key-value tuples.

After this, we will use the for loop and square brackets to iterate over each key-value pair and append it to the existing Python dictionary.

# Defining a dictionary in Python countries_hdi = < 'Canada': 0.937, 'United Kingdom': 0.935, 'United States': 0.921, >print("Original Dictionary:", countries_hdi) # Defining new key-value pairs new_items = [('Australia', 0.941), ('Switzerland', 0.962)] # Using for loop to append key-value pair for key, value in new_items: countries_hdiPython dict append to key = value print("Dictionary after adding data:", countries_hdi)

Once we execute the above Python program, we will get the following result.

Original Dictionary: Dictionary after adding data: 'Australia': 0.941, 'Switzerland': 0.962>

In this section, we understood how to add or append key-value pairs to the dictionary using for loop and square brackets in Python.

Method 5: Python Dictionary Append using dict.update()

The dict.update() is a built-in dictionary method in Python that allows to add new values to an existing dictionary.

Here is an example of using the dict.update() to add key-value pairs to an existing Python dictionary.

# Defining a dictionary in Python countries_hdi = < 'Canada': 0.937, 'United Kingdom': 0.935, 'United States': 0.921, >print("Original Dictionary:", countries_hdi) # Appending key-value using update() method countries_hdi.update() print("Dictionary after appending data:", countries_hdi)

In the example, we are appending the key-value pair to the countries_hdi dictionary.

Original Dictionary: Dictionary after appending data: 'Switzerland': 0.962>

In this section, we understood how to add or append key-value pairs to the dictionary using dict.update() in Python.

Method 6: Python Dictionary Append using append() method

Till now, we were focusing only on appending key-value pairs to an existing dictionary. However, here we will see how to append more values to an existing key in the Python Dictionary.

For this, we can use the append() method in Python.

The append() is a built-in list method in Python that allows appending more values to an existing list. If in a dictionary, a key holds a list of values, we can use the append() method to append more values to the list.

# Defining a dictionary in Python user_data = < 'Name': 'Alex', 'Age': 32, 'City': 'Chicago', 'Country': 'United States', 'Technical Skills': ['SQL', 'Java'] >print("Original Dictionary:", user_data) # Using append() method to append elements to list user_data['Technical Skills'].append('Python') user_data['Technical Skills'].append('Salesforce') print("Dictionary after appending data:", user_data)

Once we execute the python program, we will get the following result.

Python Dictionary Append Example

At the end of this section, we understood to append values to an existing Python DIctionary Key using append().

Method 7: Python Dictionary Append using extend() method

In the previous example, we have seen how to append new values to an existing key in Python Dictionary. However, by using the above approach, we have to manually append each element to a dictionary key.

So, to overcome this issue, we can use the extend() method in Python. The extend() is a built-in list method that allows appending multiple values to a list.

Here we have illustrated the example of using the extend() method in Python.

# Defining a dictionary in Python user_data = < 'Name': 'Alex', 'Age': 32, 'City': 'Chicago', 'Country': 'United States', 'Technical Skills': ['SQL', 'Java'] >print("Original Dictionary:", user_data) # Using extend() method to append elements to list user_data['Technical Skills'].extend(['Python', 'Salesforce']) print("Dictionary after appending data:", user_data)

In the above example, we appended 2 values to the Technical Skills key in the user_data dictionary.

Python Dictionary Append

In this section, we understood to append values to an existing Python DIctionary Key using extend().

You may also like to read the following Python tutorials.

Conclusion

At the end of this Python tutorial, we understood how to append key-value pairs to an existing Python Dictionary. Moreover, we have illustrated the following 7 methods for Python Dictionary Append.

  1. Using append() method
  2. Using dict.update() method
  3. Using extend() method
  4. Using for loop
  5. Using square brackets
  6. Using dictionary comprehension
  7. Using dict() constructor

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Append value to an existing key in a Python dictionary

In this post, we are going to understand the dictionary append() method and How to Append a value to an existing key in a Python dictionary. The Python dictionary is a key-value pair collection. In which the key is unique but values can be duplicated.

Append value to an existing key in a Python dictionary

We will do this job by using the following techniques.

  • Convert key type to list.
  • Define a dictionary with a key of list type
  • Define dictionary using collections.defaultdict(type)

1. Append value to an existing key by Convert a key to list type

The append () method is used to append values to the existing key in the python dictionary. We need to search the key on which we want to append a value.

We are defining a function val_append() with three arguments key, dictionary, value. We have the existing key ‘Students’ in the dict_sub, but it is not the key of the list type. We are checking first by using isinstance() method what is the type of key. If it is not the list type, We are converting it to the list type and appending the value to it. Let us understand with an example:

dict_sub = <'math':100,'Eng':100,'Chem':98,'students':[]>print('type of key =\n',type(dict_sub['students'])) dict_sub['students'].append('rack') print('after adding value to dictionary =\n',dict_sub)

This is output after appending the value ‘rack’ to ‘students’ key.We are checking the type of ‘students’ key,as it is showing it as list type.

type of key = after adding value to dictionary =

3. Append a nested list of values to the existing dictionary’s key

In this code example, we are appending nested list to the key ‘student’ .

dict_sub = <'math':100,'Eng':100,'Chem':98,'students':[]>print('type of key =\n',type(dict_sub['students'])) student_list = ['Tor','Sdney','Max','Sack'] dict_sub['students'].append(student_list) print('after adding value to dictionary =\n',dict_sub)

This is output after appending nested list to ‘students’ key.

type of key = after adding value to dictionary =

4.Append value to an existing key to a dictionary of collections.defaultdict(type)

The defaultdict is defined in the collection module, which is a subclass of dict class, and initialize with a function, its functionality is almost the same as a dictionary. The defaultdict does not raise a keyError, because it initializes a dictionary that has default values for nonexistence key.The type of values is decided based on the type passed as an argument. Defaultdict has a list, set, int for values type. So in the DefaultDict the existence of a key is not required.

How does it work?

In this code example, we are creating a defaultdict dictionary that can have values of list type. Because values type is decided based on datatype we pass while initializing the dictionary.

Now we are appending values to list type values using append() method,We have appended two values in students key.

from collections import defaultdict dict_sub = defaultdict(list) dict_sub['students'].append('rack') dict_sub['students'].append('Jack') print('after adding value to dictionary =\n',dict_sub)

This is output after appending two values ‘rack’,’jack’ to ‘students’ key.

after adding value to dictionary = defaultdict(, )

Conclusion:

We have understood how to Append value to an existing key in a Python dictionary by using the append() method. So by using this method we can easily add values to an existing key or append the nested values list to the existing key.

Источник

Оцените статью