Adding element to dictionary in python

Python Dictionary Append: How to Add Key/Value Pair

Dictionary is one of the important data types available in Python. The data in a dictionary is stored as a key/value pair. It is separated by a colon(:), and the key/value pair is separated by comma(,).

The keys in a dictionary are unique and can be a string, integer, tuple, etc. The values can be a list or list within a list, numbers, string, etc.

Here is an example of a dictionary:

Restrictions on Key Dictionaries

Here is a list of restrictions on the key in a dictionary:

  • If there is a duplicate key defined in a dictionary, the last is considered. For example consider dictionary my_dict = ;. It has a key “Name” defined twice with value as ABC and XYZ. The preference will be given to the last one defined, i.e., “Name”: “XYZ.”
  • The data-type for your key can be a number, string, float, boolean, tuples, built-in objects like class and functions. For example my_dict = ;Only thing that is not allowed is, you cannot defined a key in square brackets for example my_dict = ;
Читайте также:  Install java jdk and jre

How to append an element to a key in a dictionary with Python?

We can make use of the built-in function append() to add elements to the keys in the dictionary. To add element using append() to the dictionary, we have first to find the key to which we need to append to.

Consider you have a dictionary as follows:

The keys in the dictionary are Name, Address and Age. Usingappend() methodwe canupdate the values for the keys in the dictionary.

my_dict = <"Name":[],"Address":[],"Age":[]>; my_dict["Name"].append("Guru") my_dict["Address"].append("Mumbai") my_dict["Age"].append(30) print(my_dict)

When we print the dictionary after updating the values, the output is as follows:

Accessing elements of a dictionary

The data inside a dictionary is available in a key/value pair. To access the elements from a dictionary, you need to use square brackets ([‘key’]) with the key inside it.

Here is an example that shows to accesselements from the dictionary by using the key in the square bracket.

my_dict = print("username :", my_dict['username']) print("email : ", my_dict["email"]) print("location : ", my_dict["location"])
username : XYZ email : xyz@gmail.com location : Mumbai

If you try to use a key that is not existing in the dictionary , it will throw an error as shown below:

my_dict = print("name :", my_dict['name'])
Traceback (most recent call last): File "display.py", line 2, in print("name :", my_dict['name']) KeyError: 'name'

Deleting element(s) in a dictionary

To delete an element from a dictionary, you have to make use of the del keyword.

del dict['yourkey'] # This will remove the element with your key.

To delete the entire dictionary, you again can make use of the del keyword as shown below:

del my_dict # this will delete the dictionary with name my_dict

To just empty the dictionary or clear the contents inside the dictionary you can makeuse of clear() method on your dictionaryas shown below:

Here is a working example that shows the deletion of element, to clear the dict contents and to delete entire dictionary.

my_dict = del my_dict['username'] # it will remove "username": "XYZ" from my_dict print(my_dict) my_dict.clear() # till will make the dictionarymy_dictempty print(my_dict) delmy_dict # this will delete the dictionarymy_dict print(my_dict)
 <> Traceback (most recent call last): File "main.py", line 7, in print(my_dict) NameError: name 'my_dict' is not defined

Deleting Element(s) from dictionary using pop() method

In addition to the del keyword, you can also make use of dict.pop() method to remove an element from the dictionary. The pop() is a built-in method available with a dictionary that helps to delete the element based on the key given.

The pop() method returns the element removed for the given key, and if the given key is not present, it will return the defaultvalue. If the defaultvalue is not given and the key is not present in the dictionary, it will throw an error.

Here is a working example that shows using of dict.pop() to delete an element.

my_dict = my_dict.pop("username") print(my_dict)

Appending element(s) to a dictionary

To append an element to an existing dictionary, you have to use the dictionary name followed by square brackets with the key name and assign a value to it.

Here is an example of the same:

my_dict = my_dict['name']='Nick' print(my_dict)

Updating existing element(s) in a dictionary

To update the existing elements inside a dictionary, you need a reference to the key you want the value to be updated.

We would like to update the username from XYZ to ABC . Here is an example that shows how you can update it.

my_dict = my_dict["username"] = "ABC" print(my_dict)

Insert a dictionary into another dictionary

Consider you have two dictionaries as shown below:

Now I want my_dict1 dictionary to be inserted into my_dict dictionary. To do that lets create a key called “name” in my_dict and assign my_dict1 dictionary to it.

Here is a working example that shows inserting my_dict1 dictionary into my_dict.

my_dict = my_dict1 = my_dict["name"] = my_dict1 print(my_dict)

Now if you see the key “name”, it has the dictionary my_dict1.

Summary

  • Dictionary is one of the important data types available in Python. The data in a dictionary is stored as a key/value pair. The key/value is separated by a colon(:), and the key/value pair is separated by comma(,). The keys in a dictionary are unique and can be a string, integer, tuple, etc. The values can be a list or list within a list, numbers, string, etc. When working with lists, you might want to sort them. In that case, you can learn more about Python list sorting in this informative article.

Important built-in methods on a dictionary:

Method Description
clear() It will remove all the elements from the dictionary.
append() It is a built-in function in Python that helps to update the values for the keys in the dictionary.
update() The update() method will help us to merge one dictionary with another.
pop() Removes the element from the dictionary.

Источник

Python: How to Add Items to Dictionary

Dictionaries are Python’s built-in data types for storing key-value pairs. The dictionary elements are changeable and don’t allow duplicates. In Python 3.7 and higher, dictionary items are ordered. Lower versions of Python treat dictionary elements as unordered.

Depending on the desired result and given data, there are various ways to add items to a dictionary.

This guide shows how to add items to a Python dictionary through examples.

Python: How To Add Items To A Dictionary

  • Python version 3.7 or higher.
  • A text editor or IDE to write code.
  • A method to run the code, such as a terminal or IDE.

How to Add an Item to a Dictionary in Python

To test out different methods of adding items to a dictionary, create a dictionary with two items. Use the following code:

The methods below show how to add one or multiple items to a Python dictionary.

Note: Adding an item with an existing key replaces the dictionary item with a new value. Make sure to provide unique keys to avoid overwriting data.

Method 1: Using The Assignment Operator

The assignment operator sets a value to a key using the following syntax:

dictionary_nameAdding element to dictionary in python = value

The assignment operator adds a new key-value pair if the key does not exist.

The following code demonstrates how to add an item to a Python dictionary using the assignment operator:

my_dictionary = < "one": 1, "two": 2 >print("Before:", my_dictionary) my_dictionary["tree"] = 3 print("After:", my_dictionary)

Python add item to dictionary assignment

The code outputs the dictionary contents before and after adding a new item.

Method 2: Using update()

The update() method updates an existing dictionary with a new dictionary item:

The method accepts one or multiple key-value pairs, which is convenient for adding more than one element.

The example code looks like the following:

my_dictionary = < "one": 1, "two": 2 >print("Before:", my_dictionary) my_dictionary.update() print("After:", my_dictionary)

Python add item to dictionary update method

Use this method to add multiple new items or append a dictionary to an existing one.

Method 3: Using __setitem__

The __setitem__ method is another way to append a new dictionary item:

dictionary_name.__setitem__(key,value)
my_dictionary = < "one": 1, "two": 2 >print("Before:", my_dictionary) my_dictionary.__setitem__("three", 3) print("After:", my_dictionary)

Python add item to dictionary setitem method

The method sets the item key as «three» with the value 3 .

Method 4: Using The ** Operator

The ** operator helps merge an existing dictionary into a new dictionary and adds additional items. The syntax is:

For example, to copy an existing dictionary and append a new item to a new one, see the following code:

my_dictionary = < "one": 1, "two": 2 >my_new_dictionary = <**my_dictionary, **<"three":3>> print("Old:", my_dictionary) print("New:", my_new_dictionary)

Python add item to dictionary copy

The new dictionary contains the added item, preserving the old dictionary values. Use this method to avoid changing existing dictionaries.

Method 5: Checking If A Key Exists

Use an if statement to check whether a key exists before adding a new item to a dictionary. The example syntax is:

if key not in dictionary_name: dictionary_nameAdding element to dictionary in python = value
my_dictionary = < "one": 1, "two": 2 >print("Before:", my_dictionary) if "three" not in my_dictionary: my_dictionary["three"] = 3 print("After:", my_dictionary)

Python add item to dictionary if not in statement

The code checks whether a key with the provided name exists before adding the item to the dictionary. If the provided key exists, the existing key value does not update, and the dictionary stays unchanged.

Method 6: Using A For Loop

Add key-value pairs to a nested list and loop through the list to add multiple items to a dictionary. For example:

my_dictionary = < "one": 1, "two": 2 >my_list = [["three", 3], ["four", 4]] print("Before:", my_dictionary) for key,value in my_list: my_dictionaryAdding element to dictionary in python = value print("After:", my_dictionary)

Python add item to dictionary nested list

The for loop goes through the pairs inside the list and adds two new elements.

Note: For loop and a counter are also used as one of the methods to identify the length of a list. Learn more by visiting our guide How to Find the List Length in Python.

Method 7: Using zip

Use zip to create key-value pairs from two lists. The first list contains keys and the second contains the values.

my_dictionary = < "one": 1, "two": 2 >my_keys = ["three", "four"] my_values = [3, 4] print("Before:", my_dictionary) for key,value in zip(my_keys, my_values): my_dictionaryAdding element to dictionary in python = value print("After:", my_dictionary)

Python add item to dictionary zip

The zip function matches elements from two lists by index, creating key-value pairs.

How to Update a Python Dictionary

Update Python dictionary values using the same syntax as adding a new element. Provide the key name of an existing key, for example:

my_dictionary = < "one": 1, "two": 2 >print("Before:", my_dictionary) my_dictionary["one"] = 3 print("After:", my_dictionary)

Since Python does not allow duplicate entries in a dictionary, the code updates the value for the provided key and overwrites the existing information.

After going through the examples in this tutorial, you know how to add items to a Python dictionary. All methods provide unique functionalities, so choose a way that best suits your program and situation.

For more Python tutorial refer to our article and find out how to pretty print a JSON file using Python.

Источник

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