How to Add Key/Value Pair


Python dictionary is a collection type that stores data in key-value pairs. It is unordered, changeable, and does not allow duplicates. Dictionaries are very efficient for looking up and inserting data, as they use a technique called hashing to map keys to their associated values. They are a robust data structure that allows you to store and manipulate data in a key-value pair format. One common task when working with dictionaries is to append new values to an existing dictionary. While Python dictionaries do not have an append() method like lists do, several ways exist to add new key-value pairs to a dictionary. In this blog post, we will explore some of these methods and discuss when to use each one. So, let’s dive in!

Dictionary in Python

A dictionary is a necessary data type in Python programming. It is a collection of data values that are unordered. Python dictionary is used to store items in which each item has a key-value pair. The dictionary is made up of these key-value pairs, and this makes the dictionary more optimized. 

For example –

Dict = {1: 'Learning', 2: 'For', 3: 'Life'}
print(Dict)

Here, 

The colon is used to pair keys with the values.

The comma is used as a separator for the elements. 

The output is:

{1: ‘Learnings’, 2: ‘For’, 3: ‘Life’}

Python dictionary append is simply used to add key/value to the existing dictionary. The dictionary objects are mutable. Unlike other objects, the dictionary simply stores a key along with its value. Therefore, the combination of a key and its subsequent value represents a single element in the Python dictionary.  

Restrictions on Key Dictionaries

Below are enlisted some restrictions on the key dictionaries –

  • A given key appears only once in a dictionary. Duplicates of keys are not allowed. 
  • It won’t make sense if you map a particular key more than once. This is so because the dictionary will map each key to its value.
  • In case of a duplication of a key, the last one will be considered.
  • If a key is specified a second time after the creation of a dictionary, then the second time will be considered as it will override the first time.
  • The key must be immutable, meaning the data type can be an integer, string, tuple, boolean, etc. Therefore, lists or another dictionary can not be used as they are changeable.  

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

Creating a Dictionary

In Python, you can create a dictionary easily using fixed keys and values. The sequence of elements is placed within curly brackets, and key: values are separated by commas. It must be noted that the value of keys can be repeated but can not have duplicates. Also, keys should have immutable data types such as strings, tuples, or numbers. 

Here’s an example –

# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Learning', 2: 'For', 3: Life}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
  
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': ‘Great Learning’, 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)

The output is :

Dictionary with the use of Integer Keys: 

{1: ‘Learning’, 2: ‘For’, 3: ‘Life’}

Dictionary with the use of Mixed Keys: 

{‘Name’: ‘GreatLearning’, 1: [1, 2, 3, 4]}

Dictionary with integer keys

Here’s how to create a dictionary using the integer keys –

# creating the dictionary
dict_a = {1 : "India", 2 : "UK", 3 : "US", 4 : "Canada"}

# printing the dictionary
print("Dictionary \'dict_a\' is...")
print(dict_a)

# printing the keys only
print("Dictionary \'dict_a\' keys...")
for x in dict_a:
    print(x)

# printing the values only
print("Dictionary \'dict_a\' values...")
for x in dict_a.values():
    print(x)

# printing the keys & values
print("Dictionary \'dict_a\' keys & values...")
for x, y in dict_a.items():
    print(x, ':', y)

The output is:

Dictionary ‘dict_a’ is…

{1: ‘India’, 2: ‘USA’, 3: ‘UK’, 4: ‘Canada’}

Dictionary ‘dict_a’ keys…

1

2

3

4

Dictionary ‘dict_a’ values…

India

USA

UK

Canada

Dictionary ‘dict_a’ keys & values…

1 : India

2 : UK

3 : US

4 : Canada

Accessing elements of a dictionary

Key names are used to access elements of a dictionary. To access the elements, you need to use square brackets ([‘key’]) with the key inside it. 

Here’s an example –

# Python program to demonstrate
# accessing an element from a dictionary
  
# Creating a Dictionary
Dict = {1: 'Learning', 'name': 'For', 3: 'Life'}
  
# accessing an element using key
print("Accessing an element using key:")
print(Dict['name'])
  
# accessing an element using key
print("Accessing an element using key:")
print(Dict[1])

The output is:

Accessing an element using key:

For

Accessing an element using key:

Life

Alternative method 

There’s another method called get() that is used to access elements from a dictionary. In this method, the key is accepted as an argument and returned with a value. 

Here’s an example –

# Creating a Dictionary
Dict = {1: 'Learning', 'name': 'For', 3: 'Life'}
  
# accessing an element using get()
# method
print("Accessing an element using get:")
print(Dict.get(3))

The output is:

Accessing an element using get:

Life

Deleting element(s) in a dictionary

You can delete elements in a dictionary using the ‘del’ keyword.

The syntax is –

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

Use the following syntax to delete the entire dictionary –

del my_dict  # this will delete the dictionary with name my_dict

Another alternative is to use the clear() method. This method helps to clean the content inside the dictionary and empty it. The syntax is –

Let us check an example of the deletion of elements that result in emptying the entire dictionary –

my_dict = {"username": "ABC", "email": "abc@gmail.com", "location":"Gurgaon"}
del my_dict['username']  # it will remove "username": "ABC" 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)

The output is:

{’email’: ‘abc@gmail.com’, ‘location’: ‘Gurgaon’}

{}

Traceback (most recent call last):

  File “main.py”, line 7, in <module>

    print(my_dict)

NameError: name ‘my_dict’ is not defined

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

The dict.pop() method is also used to delete elements from a dictionary. Using the built-in pop() method, you can easily delete an element based on its given key. The syntax is:

dict.pop(key, defaultvalue)

The pop() method returns the value of the removed key. In case of the absence of the given key, it will return the default value. If neither the default value nor the key is present, it will give an error. 

Here’s an example that shows the deletion of elements using dict.pop() –

my_dict = {"username": "ABC", "email": "abc@gmail.com", "location":"Gurgaon"}
my_dict.pop("username")
print(my_dict)

The output is:

{’email’: ‘abc@gmail.com’, ‘location’: ‘Gurgaon’}

Appending element(s) to a dictionary

It is easy to append elements to the existing dictionary using the dictionary name followed by square brackets with a key inside it and assigning a value to it. 

Here’s an example:

my_dict = {"username": "ABC", "email": "abc@gmail.com", "location":"Gurgaon"}

my_dict['name']='Nick'

print(my_dict)

The output is:

{‘username’: ‘ABC’, ’email’: ‘abc@gmail.com’, ‘location’: ‘Gurgaon’, ‘name’: ‘Nick’}

Updating existing element(s) in a dictionary

For updating the existing elements in a dictionary, you need a reference to the key whose value needs to be updated. 

In this example, we will update the username from ABC to XYZ. Here’s how to do it:

my_dict = {"username": "ABC", "email": "abc@gmail.com", "location":"Gurgaon"}

my_dict["username"] = "XYZ"

print(my_dict)

The output is:

{‘username’: ‘XYZ’, ’email’: ‘abc@gmail.com’, ‘location’: ‘Gurgaon’}

Insert a dictionary into another dictionary

Let us consider an example with two dictionaries – Dictionary 1 and Dictionary 2 as shown below –

Dictionary 1:

my_dict = {“username”: “ABC”, “email”: “abc@gmail.com”, “location”:”Gurgaon”}

Dictionary 2:

my_dict1 = {“firstName” : “Nick”, “lastName”: “Jonas”}

Now we want to merge Dictionary 1 into Dictionary 2. This can be done by creating a key called “name” in my_dict and assigning my_dict1 dictionary to it. Here’s how to do it:

my_dict = {"username": "ABC", "email": "abc@gmail.com", "location":"Gurgaon"}

my_dict1 = {"firstName" : "Nick", "lastName": "Jonas"}

my_dict["name"] = my_dict1

print(my_dict)

The output is:

{‘username’: ‘ABC’, ’email’: ‘abc@gmail.com’, ‘location’: ‘Gurgaon’, ‘name’: {‘firstName’: ‘Nick’, ‘lastName’: Jonas}}

As observed in the output, the key ‘name’ has the dictionary my_dict1. 

Quick Programs on Python Dictionary Append

  1. Restrictions on Key Dictionaries:

Python dictionaries have some restrictions on their keys. Here are some examples of invalid dictionary keys:

bashCopy codemy_dict = {[1,2]: 'value'}  # Lists are unhashable and cannot be used as keys
my_dict = {{1:2}: 'value'}  # Dictionaries are unhashable and cannot be used as keys
my_dict = {'a': 'value1', 'a': 'value2'}  # Duplicate keys are not allowed in dictionaries
  1. How to append an element to a key in a dictionary with Python:

You can append an element to a list that is a value associated with a key in a dictionary like this:

cssCopy codemy_dict = {'key': [1, 2, 3]}
my_dict['key'].append(4)
print(my_dict)  # Output: {'key': [1, 2, 3, 4]}
  1. Accessing elements of a dictionary:

You can access elements in a dictionary using their keys like this:

bashCopy codemy_dict = {'key1': 'value1', 'key2': 'value2'}
print(my_dict['key1'])  # Output: 'value1'

You can also use the get() method to access dictionary elements. This method returns None if the key is not present in the dictionary:

bashCopy codemy_dict = {'key1': 'value1', 'key2': 'value2'}
print(my_dict.get('key1'))  # Output: 'value1'
print(my_dict.get('key3'))  # Output: None
  1. Deleting element(s) in a dictionary:

You can delete an element from a dictionary using the del keyword like this:

cssCopy codemy_dict = {'key1': 'value1', 'key2': 'value2'}
del my_dict['key1']
print(my_dict)  # Output: {'key2': 'value2'}
  1. Deleting Element(s) from dictionary using pop() method:

You can also delete an element from a dictionary using the pop() method. This method removes the key-value pair from the dictionary and returns the value:

goCopy codemy_dict = {'key1': 'value1', 'key2': 'value2'}
value = my_dict.pop('key1')
print(my_dict)  # Output: {'key2': 'value2'}
print(value)  # Output: 'value1'
  1. Appending element(s) to a dictionary:

You can append a new key-value pair to a dictionary like this:

cssCopy codemy_dict = {'key1': 'value1'}
my_dict['key2'] = 'value2'
print(my_dict)  # Output: {'key1': 'value1', 'key2': 'value2'}
  1. Updating existing element(s) in a dictionary:

You can update an existing element in a dictionary by assigning a new value to its key like this:

cssCopy codemy_dict = {'key1': 'value1', 'key2': 'value2'}
my_dict['key2'] = 'new_value'
print(my_dict)  # Output: {'key1': 'value1', 'key2': 'new_value'}
  1. Insert a dictionary into another dictionary:

You can insert a dictionary into another dictionary by using the update() method like this:

bashCopy codemy_dict1 = {'key1': 'value1'}
my_dict2 = {'key2': 'value2'}
my_dict1.update(my_dict2)
print(my_dict1)  # Output:

Embarking on a journey towards a career in data science opens up a world of limitless possibilities. Whether you’re an aspiring data scientist or someone intrigued by the power of data, understanding the key factors that contribute to success in this field is crucial. The below path will guide you to become a proficient data scientist.

FAQs

Can you append to a dictionary in Python?

Yes, you can append to a dictionary in Python. It is done using the update() method. The update() method links one dictionary with another, and the method involves inserting key-value pairs from one dictionary into another dictionary. 

How do I add data to a dictionary in Python?

You can add data or values to a dictionary in Python using the following steps:
First, assign a value to a new key.
Use dict. Update() method to add multiple values to the keys.
Use the merge operator (I) if you are using Python 3.9+ 
Create a custom function 

Does append work for dictionaries?

Yes, append works for dictionaries in Python. This can be done using the update() function and [] operator. 

How do I append to a dictionary key?

To append to a dictionary key in Python, use the following steps:
1. Converting an existing key to a list type to append value to that key using the append() method.
2. Append a list of values to the existing dictionary’s keys.

How do you append an empty dictionary in Python?

Appending an empty dictionary means adding a key-value pair to that dictionary. This can be done using the dict[key] method. 
Here’s how to do it:
a_dict = {}
a_dict[“key”] = “value”
print(a_dict)
The output is:
{‘key’: ‘value’}

How do you add value to a key in Python?

Using the update() function and [] operator, you can add or append a new key value to the dictionary. This method can also be used to replace the value of any existing key or append new values to the keys. 

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img