Python Dictionary Append: How To Add Key/Value Pair?

python dictionary append

Ever found yourself needing to add new key-value pairs to a Python dictionary? 

As one of Python’s most versatile data structures, dictionaries offer a powerful way to store and modify data in a key-value format. 

But how exactly can we append new values to an existing dictionary? 

While dictionaries lack an append() method like lists, several methods can effectively accomplish this task. 

In this blog post, we’ll delve into Python dictionary append methods and explore some techniques for adding new key-value pairs to dictionaries in Python.

Join our “Free Functions in Python” course and master the fundamentals!

Dictionary In Python

In Python, a dictionary is a vital data type that efficiently stores data in key-value pairs. These pairs enable easy and optimized data retrieval and manipulation. Let’s break down what a Python dict append offers:

Unordered Collection: Unlike lists, dictionaries don’t follow a specific order.

Key-Value Pairs: Each item in a dictionary consists of a key and its associated value.

Efficient Lookup and Insertion: Dictionaries leverage hashing for fast access and insertion of data.

A Python dictionary is created using curly braces {}, with key-value pairs separated by colons (:). For example:

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

This results in:

{1: 'Learning', 2: 'For', 3: 'Life'}

When it comes to Python dictionary append, it’s all about adding new key-value pairs to an existing dictionary. They have a robust data structure that allows you to store and retrieve data efficiently through key-value pairs.

Here is an example for a better understanding of Python append to dictionary:

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

This results in:

{1: 'Learning', 2: 'For', 3: 'Life', 4: 'Growth'}

Python append dictionary allows seamless expansion of dictionaries by associating new keys with their respective values. It’s a powerful feature in Python’s arsenal for managing data efficiently.

Take your first step towards becoming a Python pro with our free Python courses.

Restrictions On Key Dictionaries

Unique Keys

  • Each key in a dictionary must be unique. Duplicates are not allowed.
  • Keys need to be unique to maintain the integrity of the dictionary’s structure and functionality.

Last Key Override

  • The previous occurrence will prevail if a key is duplicated in a dictionary.
  • This ensures consistency and predictability in how keys are associated with values.

Immutability Requirement

  • Keys in a dictionary must be of immutable data types such as integers, strings, tuples, or booleans.
  • Immutable keys guarantee stability and prevent unintended modifications to the dictionary’s structure.

No Lists or Dictionaries as Keys

  • Mutable data types like lists or dictionaries cannot be used as keys.
  • This restriction ensures the integrity of the dictionary’s key-value mappings, as mutable keys could lead to unexpected changes.

Discover how the Top 30 Python Libraries can help you overcome Python limitations.

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]}

Watch the following video to gain a deeper understanding of Python dictionaries.

Also must read our blog on Python Dictionary – Everything you need to Know

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 –

your_dict.clear()

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. 

Don’t just learn Python, master it with our ‘Python Fundamentals for Beginners Course’

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:

my_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:

my_dict = {'key': [1, 2, 3]}
my_dict['key'].append(4)
print(my_dict)  # Output: {'key': [1, 2, 3, 4]}

Learn what lists are and how they work in our free Python List course 

  1. Accessing Elements Of A Dictionary

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

my_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:

my_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:

my_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:

my_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:

my_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:

my_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:

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

Wrapping up 

Becoming proficient in appending key/value pairs in Python dictionaries is a fundamental skill for any aspiring programmer. 

Whether you’re a beginner or an experienced coder, understanding Python append to dict and how to manipulate dictionaries efficiently is crucial. By following the simple steps outlined in this guide, you can confidently add new entries to your dictionaries and enhance the functionality of your Python programs.

Also, if you’re interested in diving deeper into Python programming and exploring its applications in high-demand fields like data science, a world of opportunity is waiting for you. 

By enrolling in a comprehensive Data Science Course offered by Great Learning, you can gain practical insights into how Python is utilized in real-world applications. 

Whether aiming to advance your career or expand your knowledge, Great Learning courses provide hands-on experience and expert guidance that help you embark on a journey toward a promising future.

FAQs

What if I want to append multiple key-value pairs from one dictionary to another?

When you have two dictionaries and you want to append key-value to dictionary python, the update() method is a handy tool. It allows you to merge the contents of one dictionary into another.

Here’s how it works:

1. Merging Dictionaries
Let’s say you have two dictionaries, dict1 and dict2, and you want to append all key-value pairs from dict2 into dict1. Instead of iterating over dict2 and adding each key-value pair individually, you can simply use the update() method.

2. Overwriting Existing Keys
If the dictionaries share some keys, the update() method will overwrite the values of the keys that are common between them. This means if there are keys in dict2 that already exist in dict1, the values in dict1 will be replaced by the values from dict2.

3. Efficient and Clean
Using update() is more efficient and cleaner compared to manual iteration, especially when dealing with large dictionaries. It’s a one-liner that achieves the same result without the need for additional loops or conditions.

Overall, the update() method is a convenient way in dictionary append python to combine dictionaries, ensuring that you efficiently append multiple key-value pairs from one dictionary to another while handling key conflicts gracefully.

Can I append one dictionary to another in Python without overwriting existing keys?

Yes, you can. When you use the update() method to append dictionary python, existing keys are updated with new values, but if there are any new keys, they are added to the dictionary without overwriting existing ones.

Can I add a single key-value pair to a dictionary in Python?

Yes, you can. To append to dictionary python with a single key-value pair, you can simply assign a value to a new key in the dictionary. If the key already exists, the value associated with it will be updated.

→ Explore this Curated Program for You ←

Avatar photo
Great Learning Editorial Team
The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.

Full Stack Software Development Course from UT Austin

Learn full-stack development and build modern web applications through hands-on projects. Earn a certificate from UT Austin to enhance your career in tech.

4.8 ★ Ratings

Course Duration : 28 Weeks

Cloud Computing PG Program by Great Lakes

Enroll in India's top-rated Cloud Program for comprehensive learning. Earn a prestigious certificate and become proficient in 120+ cloud services. Access live mentorship and dedicated career support.

4.62 ★ (2,760 Ratings)

Course Duration : 8 months

Scroll to Top