Python: How to Add Keys to a Dictionary

python assign keys to dictionary

  • Introduction

A dictionary in Python is a collection of items that store data as key-value pairs. We can access and manipulate dictionary items based on their key. Dictionaries are mutable and allow us to add new items to them.

The quickest way to add a single item to a dictionary is by using a dictionary's index with a new key and assigning a value. For example, we add a new key-value pair like this:

Python allows adding multiple items to dictionaries as well. In this tutorial, we'll take a look at how to add keys to a dictionary in Python .

  • Add Key to a Python Dictionary

There are multiple ways to add a new key-value pair to an existing dictionary. Let's have a look at a few common ways to do so.

  • Add Key with Value

We can add a new key to a dictionary by assigning a value to it. If the key is already present, it overwrites the value it points to. The key has to be written in subscript notation to the dictionary like this:

This key-value pair will be added to the dictionary. If you're using Python 3.6 or later, it will be added as the last item of the dictionary.

Let's make a dictionary, and then add a new key-value pair with this approach:

This will result in:

  • Add Key to Dictionary without Value

If you'd just like to add a key, without a value, you can simply put None instead of the value, with any of the methods covered in this article:

This results in:

  • Add Multiple Key-Value Pairs with update()

In Python, we can add multiple key-value pairs to an existing dictionary. This is achieved by using the update() method. This method takes an argument of type dict or any iterable that has the length of two - like ((key1, value1),) , and updates the dictionary with new key-value pairs.

If the key is already present in the dictionary, it gets overwritten with the new value.

The keys can also be passed as keyword arguments to this method with their corresponding values, like dictionary.update(new_key=new_value) .

Note: This is arguably the most popular method of adding new keys and values to a dictionary.

Let's use the update() method to add multiple key-value pairs to a dictionary:

Running this code will produce the following output:

  • Using Merge Operator (Python 3.9+)

From Python version 3.9, Merge ( | ) and Update ( |= ) operators have been added to the built-in dict class.

These are very convenient methods to add multiple key-value pairs to a dictionary. The Merge ( | ) operator creates a new dictionary with the keys and values of both of the given dictionaries. We can then assign this result to a new dictionary.

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Whereas the Update ( |= ) operator, adds the key-value pairs of the second dictionary into the first dictionary. So, the existing dictionary gets updated with multiple key-value pairs from another dictionary.

Here's an example of using Merge ( | ) and Update ( |= ) operators to add new keys to a dictionary:

This code will produce the following output on the Python(3.9+) interpreter:

In this tutorial, we learned how we can add a new key to a dictionary. We first added the key-value pair using subscript notation - we added a key to a dictionary by assigning a value to it. We then looked at the update() method to add multiple key-value pairs to a dictionary. We've also used the update() method with parameters of type dictionary, tuple, and keyword arguments. Lastly, we probed into the Merge and Update operators available from Python versions 3.9 onwards.

The update() method of dictionary proves to be the most popular way to add new keys to an existing dictionary.

You might also like...

  • Guide to Hash Tables in Python
  • Dictionaries vs Arrays in Python - Deep Dive
  • Modified Preorder Tree Traversal in Django
  • Stacks and Queues in Python
  • Python Performance Optimization

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Freelance Python Developer

In this article

python assign keys to dictionary

Graphs in Python - Theory and Implementation

Graphs are an extremely versatile data structure. More so than most people realize! Graphs can be used to model practically anything, given their nature of...

David Landup

Data Visualization in Python with Matplotlib and Pandas

Data Visualization in Python with Matplotlib and Pandas is a course designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and...

© 2013- 2023 Stack Abuse. All rights reserved.

Effortlessly Add Keys to Python Dictionaries: A Complete Guide

add keys to dictionary python

Dictionaries are a built-in data structure in Python used for mapping keys to values. They are similar to lists, but instead of using indices to access values, you use keys. In this article, we’ll explore how to add keys to dictionary in Python and how to use them effectively in your code.

Creating a Dictionary

The syntax for creating a dictionary in Python is straightforward. You enclose a comma-separated list of key-value pairs within curly braces:

Adding Keys to a Dictionary

There are several ways to add keys to a dictionary in Python. One common method is to use square brackets and assignment:

Another way to add keys to a dictionary in Python is to use the update() method:

Updating Existing Keys

If you add a key to a dictionary that already exists, the value associated with that key will be updated:

Using the get() Method

When you’re working with dictionaries, it’s important to be able to access the values associated with specific keys. One way to do this is to use square brackets:

However, this approach can cause an error if you try to access a key that doesn’t exist in the dictionary. To avoid this, you can use the get() method instead:

The get() method takes two arguments: the first is the key you want to access, and the second is an optional default value to return if the key doesn’t exist.

Add keys to a dictionary using for loop

You can add keys to a dictionary within a loop by using the dictionary’s bracket notation to access and add items. Here’s an example:

In this example, we first define an empty dictionary called my_dict . We also define a list of keys ( keys ) and a list of values ( values ). We then loop through the keys and values using a for loop that goes through the range of the length of the keys list.

Within the loop, we use the bracket notation to access the key at the current index of the keys list ( keys[i] ) and add the corresponding value from the values list ( values[i] ) as the value for that key in the dictionary ( my_dict[keys[i]] = values[i] ).

After the loop, we print the resulting dictionary, which should contain the key-value pairs from the keys and values lists.

Add keys to dictionary if not exists

To add keys to a dictionary only if they don’t already exist, you can use the setdefault() method of the dictionary. This method sets a key to a default value if the key is not already in the dictionary. Here’s an example:

In this example, we first define a dictionary called my_dict with some initial keys and values. We also define a list of keys ( keys ) and a list of values ( values ). We then loop through the keys and values using a for loop that goes through the range of the length of the keys list.

Within the loop, we use the setdefault() method to add the key-value pair to the dictionary only if the key doesn’t already exist in the dictionary. If the key already exists, the setdefault() method returns the current value for that key without changing it.

After the loop, we print the resulting dictionary, which should contain all the original keys and values from the dictionary, as well as any new key-value pairs that were added from the keys and values lists.

Add tuple as key to dictionary

You can use a tuple as a key for a dictionary in Python. Here’s an example:

we define a dictionary called my_dict with a tuple key ('a', 1) and a corresponding value 'apple' . We can access the value for this key using the bracket notation my_dict[('a', 1)] .

To add a new key-value pair with a tuple key, we can simply use the bracket notation to assign a value to a new tuple key ('b', 2) like so: my_dict[('b', 2)] = 'banana' .

Add key to dictionary using list comprehension

You can add keys to a dictionary using a list comprehension by creating a dictionary with the key-value pairs and then using dictionary comprehension to filter and add keys to the original dictionary. Here’s an example:

In this example, we define the original dictionary my_dict , and a list of keys to add keys_to_add , and a value for the new keys value .

We create a new dictionary new_dict with the key-value pairs to add, using a dictionary comprehension to create a dictionary with keys from the keys_to_add list, and a value of value .

We then use the ** operator to unpack both dictionaries ( my_dict and new_dict ) into a new dictionary. This is done in a dictionary comprehension to add the new keys to the original dictionary and any existing keys in my_dict will be overwritten with the new value of value .

Finally, we print the updated dictionary with the new keys added.

Yes, you can add a key with multiple values to a dictionary by assigning a list or another dictionary as the value.

Yes, you can add a key with a value of any data type to a dictionary, including strings, integers, floating-point numbers, lists, dictionaries, and more.

Dictionaries are a powerful tool for mapping keys to values in Python. By adding keys to dictionaries, you can store and retrieve information in a flexible and efficient way. Whether you’re using square brackets and assignment, the update() method, or the get() method, there are many ways to work with dictionaries in Python.

It’s important to keep in mind that dictionaries are unordered, which means that the keys and values may not be stored in the order you expect. However, you can use the sorted() function to sort the keys in a dictionary, or you can use the collections module to create an ordered dictionary that preserves the order of the keys.

Whether you’re a beginner or an experienced programmer, understanding dictionaries and how to add keys to them is a valuable skill to have. Try incorporating dictionaries into your own projects, and see how they can simplify your code and improve your workflow.

Trending Python Articles

LLM Chain Explained: Revolutionizing Digital Transactions and Security

Stack Vidhya

How to Add a Key To a Dictionary in Python – Definitive Guide

Python Dictionary is used to store the data in the key-value pair.

You can add a key to dictionary in python using mydict["newkey"] = "newValue" method.

This tutorial teaches you the different methods to add a key to a dictionary in Python

Table of Contents

Using Subscript Notation ( [ ] Operator)

The subscript notation is defined as square brackets [] , and it’s used to access the elements of the list or set of a dictionary.

Together with [] and = operators, you can also assign a key-value pair to an existing dictionary object.

The following code shows how to add a new key to a dictionary object.

This is also known as appending a new key value to the dictionary.

Using Update() method

In this section, you’ll learn how to add new key-value to existing dict using the update() method.

It accepts a mandatory mapping parameter which is also another dictionary consisting of one or more key-value pairs.

The following example shows how new keys and values can be added to a dictionary using the update() method.

Using __setitem()__ method

In this section, you’ll learn how to add new keys to the dictionary using the setitem() method in Python.

It is not recommended to use this method considering performance complexity.

setItem() accepts key and value as parameters and sets the value into the calling object.

The following example shows how to add a new key to a dictionary using the setitem() method.

Using ** operator

In this section, You’ll add a new Key-value Using ** operator .

This operator denotes dictionary unpacking. This operator’s operand must be a mapping .

Each mapping item is added to the new dictionary.

Using ** in front of key-value pairs like **{"five": "5"} will unpack it as a new dictionary object.

The following code shows how the ** object unpacks two dictionary objects and adds them to a new dictionary object.

Using Merge Operator

In this section, you’ll learn how to add new keys to the Python dictionary using the Python merge operator .

This merge operator is available since python version 3.9 .

You can check the Python version in cmd using the below command.

There are two types of the merge operations.

First Method using Merge

Two dictionaries will be merged and a new dictionary will be created when you use | operator between two dictionaries.

Second Method using Merge

The items from the second dictionary will be merged into the first dictionary rather than creating a new dictionary object when you use |= operator between two dictionaries.

Add new key value pair to dictionary without overwriting

In this section, you’ll learn how to add new key-value pairs to the dictionary without overwriting the existing key-value pairs.

This can be done by checking if the key already exists in the dictionary using the in operator and the if statements.

Before adding a new key to the dictionary,

  • if "one" not in mydict is used to check if the key doesn’t exist in the dictionary.
  • If this statement is evaluated to true , then the key will be added to the dictionary.
  • If evaluated to false, an error message will be printed.

In the below example, the key “ four ” is not available in the dictionary . Hence it’ll be added to the dictionary.

Add new key to dictionary without value

You can add a new key to the dictionary without value using the None keyword. It’ll just add a new key to the dictionary.

You’ll see the below output, where there is a key named keywithoutvalue exists without any value.

Additional Resources

  • How to Iterate Through Dictionary in Python?
  • How To Sort A Dictionary By Key In Python
  • How To Populate A Dictionary Using For Loop in Python

Liked the article? Then, you'd love the newsletter!

Hooray! You're on our elite list!

No spam. Unsubscribe anytime.

1 thought on “How to Add a Key To a Dictionary in Python – Definitive Guide”

It was great. Thanks Please keep on your good job and add more examples.

Leave a Comment Cancel reply

Save my name, email, and website in this browser for the next time I comment.

Notify me via e-mail if anyone answers my comment.

 Yes, add me to your mailing list

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, python introduction.

  • Getting Started
  • Keywords and Identifier
  • Python Comments
  • Python Variables

Python Data Types

  • Python Type Conversion
  • Python I/O and Import
  • Python Operators
  • Python Namespace

Python Flow Control

  • Python if...else
  • Python for Loop
  • Python while Loop
  • Python break and continue
  • Python Pass

Python Functions

  • Python Function
  • Function Argument
  • Python Recursion
  • Anonymous Function
  • Global, Local and Nonlocal
  • Python Global Keyword
  • Python Modules
  • Python Package

Python Datatypes

  • Python Numbers
  • Python List
  • Python Tuple
  • Python String

Python Dictionary

Python files.

  • Python File Operation
  • Python Directory
  • Python Exception
  • Exception Handling
  • User-defined Exception

Python Object & Class

  • Classes & Objects
  • Python Inheritance
  • Multiple Inheritance
  • Operator Overloading

Python Advanced Topics

  • Python Iterator
  • Python Generator
  • Python Closure
  • Python Decorators
  • Python Property
  • Python RegEx
  • Python Examples

Python Date and time

  • Python datetime Module
  • Python datetime.strftime()
  • Python datetime.strptime()
  • Current date & time
  • Get current time
  • Timestamp to datetime
  • Python time Module
  • Python time.sleep()

Python Tutorials

Python Dictionary clear()

Python Nested Dictionary

Python Dictionary Comprehension

  • Python Dictionary items()
  • Python Dictionary fromkeys()

In Python, a dictionary is a collection that allows us to store data in key-value pairs.

Learn Python with Challenges

Solve challenges and become a Python expert.

  • Create a Dictionary

We create dictionaries by placing key:value pairs inside curly brackets {} , separated by commas. For example,

The country_capitals dictionary has three elements (key-value pairs).

Note: Dictionary keys must be immutable, such as tuples, strings, integers, etc. We cannot use mutable (changeable) objects such as lists as keys.

Tip: We can also use Python's dict() function to create dictionaries.

  • Python Dictionary Length

We can get the size of a dictionary by using the len() function.

  • Access Dictionary Items

We can access the value of a dictionary item by placing the key inside square brackets.

Note: We can also use the get() method to access dictionary items.

  • Change Dictionary Items

Python dictionaries are mutable (changeable). We can change the value of a dictionary element by referring to its key. For example,

  • Add Items to a Dictionary

We can add an item to the dictionary by assigning a value to a new key (that does not exist in the dictionary). For example,

Note: We can also use the update method() to add or change dictionary items.

  • Remove Dictionary Items

We use the del statement to remove an element from the dictionary. For example,

Note: We can also use the pop method() to remove an item from the dictionary.

If we need to remove all items from the dictionary at once, we can use the clear() method.

  • Python Dictionary Methods

Here are some of the commonly used dictionary methods .

  • Dictionary Membership Test

We can check whether a key exists in a dictionary using the in operator.

Note: The in operator checks whether a key exists; it doesn't check whether a value exists or not.

  • Iterating Through a Dictionary

A dictionary is an ordered collection of items (starting from Python 3.7). Meaning a dictionary maintains the order of its items.

We can iterate through dictionary keys one by one using a for loop.

Table of Contents

Video: python dictionaries to store key/value pairs.

Sorry about that.

Related Tutorials

Python Tutorial

Python Library

Datagy logo

  • Learn Python
  • Python Lists
  • Python Dictionaries
  • Python Strings
  • Python Functions
  • Learn Pandas & NumPy
  • Pandas Tutorials
  • Numpy Tutorials
  • Learn Data Visualization
  • Python Seaborn
  • Python Matplotlib

Python: Add Key:Value Pair to Dictionary

  • December 6, 2021 December 19, 2022

How to Add Items to a Python Dictionary Cover Image

In this tutorial, you’ll learn how to add key:value pairs to Python dictionaries . You’ll learn how to do this by adding completely new items to a dictionary, adding values to existing keys, and dictionary items in a for loop, and using the zip() function to add items from multiple lists.

What are Python dictionaries? Python dictionaries are incredibly helpful data types, that represent a hash table, allowing data retrieval to be fast and efficient. They consist of key:value pairs, allowing you to search for a key and return its value. Python dictionaries are created using curly braces, {} . Their keys are required to be immutable and unique, while their values can be any data type (including other dictionaries) and do not have to be unique.

The Quick Answer: Use dict[key] = [value] to Add Items to a Python Dictionary

Quick Answer - Python Add Append Item to Dictionary

Table of Contents

Add an Item to a Python Dictionary

The easiest way to add an item to a Python dictionary is simply to assign a value to a new key. Python dictionaries don’t have a method by which to append a new key:value pair. Because of this, direct assignment is the primary way of adding new items to a dictionary.

Let’s take a look at how we can add an item to a dictionary:

We can see here that we were able to easily append a new key:value pair to a dictionary by directly assigning a value to a key that didn’t yet exist.

What can we set as dictionary keys? It’s important to note that we can add quite a few different items as Python dictionary keys. For example, we could make our keys strings, integers, tuples – any immutable item that doesn’t already exist. We can’t, however, use mutable items (such as lists) to our dictionary keys.

In the next section, you’ll learn how to use direct assignment to update an item in a Python dictionary.

Update an Item in a Python Dictionary

Python dictionaries require their keys to be unique. Because of this, when we try to add a key:value pair to a dictionary where the key already exists, Python updates the dictionary. This may not be immediately clear, especially since Python doesn’t throw an error.

Let’s see what this looks like, when we add a key:value pair to a dictionary where the key already exists:

We can see that when we try to add an item to a dictionary when the item’s key already exists, that the dictionary simply updates. This is because Python dictionaries require the items to be unique, meaning that it can only exist once.

In the next section, you’ll learn how to use a for loop to add multiple items to a Python dictionary.

Append Multiple Items to a Python Dictionary with a For Loop

There may be times that you want to turn two lists into a Python dictionary. This can be helpful when you get data from different sources and want to combine lists into a dictionary data structure.

Let’s see how we can loop over two lists to create a dictionary:

Here, we loop over each value from 0 through to the length of the list minus 1, to access the indices of our lists. We then access the i th index of each list and assign them to the keys and values of our lists.

There is actually a much simpler way to do this – using the Python zip function, which you’ll learn about in the next section.

Add Multiple Items to a Python Dictionary with Zip

The Python zip() function allows us to iterate over two iterables sequentially . This saves us having to use an awkward range() function to access the indices of items in the lists.

Let’s see what this looks like in Python:

The benefit of this approach is that it is much more readable. Python indices can be a difficult thing for beginner Python developers to get used to. The zip function allows us to easily interpret what is going on with our code. We can use the zip function to name our iterable elements, to more easily combine two lists into a dictionary.

If you’re working with a dictionary that already exists, Python will simply update the value of the existing key. Because Python lists can contain duplicate values, it’s important to understand this behaviour. This can often lead to unexpected results since the program doesn’t actually throw an error.

In this tutorial, you learned how to use Python to add items to a dictionary. You learned how to do this using direct assignment, which can be used to add new items or update existing items. You then also learned how to add multiple items to a dictionary using both for loops and the zip function.

To learn more about Python dictionaries, check out the official documentation here .

Additional Resources

To learn more about related topics, check out the articles below:

  • Python: Pretty Print a Dict (Dictionary) – 4 Ways
  • Python: Check if a Dictionary is Empty (5 Ways!)
  • Python: Check if a Key (or Value) Exists in a Dictionary (5 Easy Ways)
  • Python: Remove Key from Dictionary (4 Different Ways)
  • Merge Python Dictionaries – 4 Different Ways

Nik Piepenbreier

Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials. View Author posts

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Create a Dictionary in Python – Python Dict Methods

In this article, you will learn the basics of dictionaries in Python.

You will learn how to create dictionaries, access the elements inside them, and how to modify them depending on your needs.

You will also learn some of the most common built-in methods used on dictionaries.

Here is what we will cover:

  • Define an empty dictionary
  • Define a dictionary with items
  • An overview of keys and values 1. Find the number of key-value pairs contained in a dictionary 2. View all key-value pairs 3. View all keys 4. View all values
  • Access individual items
  • Add new items
  • Update items
  • Delete items

How to Create a Dictionary in Python

A dictionary in Python is made up of key-value pairs.

In the two sections that follow you will see two ways of creating a dictionary.

The first way is by using a set of curly braces, {} , and the second way is by using the built-in dict() function.

How to Create An Empty Dictionary in Python

To create an empty dictionary, first create a variable name which will be the name of the dictionary.

Then, assign the variable to an empty set of curly braces, {} .

Another way of creating an empty dictionary is to use the dict() function without passing any arguments.

It acts as a constructor and creates an empty dictionary:

How to Create A Dictionary With Items in Python

To create a dictionary with items, you need to include key-value pairs inside the curly braces.

The general syntax for this is the following:

Let's break it down:

  • dictionary_name is the variable name. This is the name the dictionary will have.
  • = is the assignment operator that assigns the key:value pair to the dictionary_name .
  • You declare a dictionary with a set of curly braces, {} .
  • Inside the curly braces you have a key-value pair. Keys are separated from their associated values with colon, : .

Let's see an example of creating a dictionary with items:

In the example above, there is a sequence of elements within the curly braces.

Specifically, there are three key-value pairs: 'name': 'Dionysia' , 'age': 28 , and 'location': 'Athens' .

The keys are name , age , and location . Their associated values are Dionysia , 28 , and Athens , respectively.

When there are multiple key-value pairs in a dictionary, each key-value pair is separated from the next with a comma, , .

Let's see another example.

Say that you want to create a dictionary with items using the dict() function this time instead.

You would achieve this by using dict() and passing the curly braces with the sequence of key-value pairs enclosed in them as an argument to the function.

It's worth mentioning the fromkeys() method, which is another way of creating a dictionary.

It takes a predefined sequence of items as an argument and returns a new dictionary with the items in the sequence set as the dictionary's specified keys.

You can optionally set a value for all the keys, but by default the value for the keys will be None .

The general syntax for the method is the following:

Let's see an example of creating a dictionary using fromkeys() without setting a value for all the keys:

Now let's see another example that sets a value that will be the same for all the keys in the dictionary:

An Overview of Keys and Values in Dictionaries in Python

Keys inside a Python dictionary can only be of a type that is immutable .

Immutable data types in Python are integers , strings , tuples , floating point numbers , and Booleans .

Dictionary keys cannot be of a type that is mutable, such as sets , lists , or dictionaries .

So, say you have the following dictionary:

The keys in the dictionary are Boolean , integer , floating point number , and string data types, which are all acceptable.

If you try to create a key which is of a mutable type you'll get an error - specifically the error will be a TypeError .

In the example above, I tried to create a key which was of list type (a mutable data type). This resulted in a TypeError: unhashable type: 'list' error.

When it comes to values inside a Python dictionary there are no restrictions. Values can be of any data type - that is they can be both of mutable and immutable types.

Another thing to note about the differences between keys and values in Python dictionaries, is the fact that keys are unique . This means that a key can only appear once in the dictionary, whereas there can be duplicate values.

How to Find the Number of key-value Pairs Contained in a Dictionary in Python

The len() function returns the total length of the object that is passed as an argument.

When a dictionary is passed as an argument to the function, it returns the total number of key-value pairs enclosed in the dictionary.

This is how you calcualte the number of key-value pairs using len() :

How to View All key-value Pairs Contained in a Dictionary in Python

To view every key-value pair that is inside a dictionary, use the built-in items() method:

The items() method returns a list of tuples that contains the key-value pairs that are inside the dictionary.

How to View All keys Contained in a Dictionary in Python

To see all of the keys that are inside a dictionary, use the built-in keys() method:

The keys() method returns a list that contains only the keys that are inside the dictionary.

How to View All values Contained in a Dictionary in Python

To see all of the values that are inside a dictionary, use the built-in values() method:

The values() method returns a list that contains only the values that are inside the dictionary.

How to Access Individual Items in A Dictionary in Python

When working with lists, you access list items by mentioning the list name and using square bracket notation. In the square brackets you specify the item's index number (or position).

You can't do exactly the same with dictionaries.

When working with dictionaries, you can't access an element by referencing its index number, since dictionaries contain key-value pairs.

Instead, you access the item by using the dictionary name and square bracket notation, but this time in the square brackets you specify a key.

Each key corresponds with a specific value, so you mention the key that is associated with the value you want to access.

The general syntax to do so is the following:

Let's look at the following example on how to access an item in a Python dictionary:

What happens though when you try to access a key that doesn't exist in the dictionary?

It results in a KeyError since there is no such key in the dictionary.

One way to avoid this from happening is to first search to see if the key is in the dictionary in the first place.

You do this by using the in keyword which returns a Boolean value. It returns True if the key is in the dictionary and False if it isn't.

Another way around this is to access items in the dictionary by using the get() method.

You pass the key you're looking for as an argument and get() returns the value that corresponds with that key.

As you notice, when you are searching for a key that does not exist, by default get() returns None instead of a KeyError .

If instead of showing that default None value you want to show a different message when a key does not exist, you can customise get() by providing a different value.

You do so by passing the new value as the second optional argument to the get() method:

Now when you are searching for a key and it is not contained in the dictionary, you will see the message This value does not exist appear on the console.

How to Modify A Dictionary in Python

Dictionaries are mutable , which means they are changeable.

They can grow and shrink throughout the life of the program.

New items can be added, already existing items can be updated with new values, and items can be deleted.

How to Add New Items to A Dictionary in Python

To add a key-value pair to a dictionary, use square bracket notation.

First, specify the name of the dictionary. Then, in square brackets, create a key and assign it a value.

Say you are starting out with an empty dictionary:

Here is how you would add a key-value pair to my_dictionary :

Here is how you would add another new key-value pair:

Keep in mind that if the key you are trying to add already exists in that dictionary and you are assigning it a different value, the key will end up being updated.

Remember that keys need to be unique.

If you want to prevent changing the value of an already existing key by accident, you might want to check if the key you are trying to add is already in the dictionary.

You do this by using the in keyword as we discussed above:

How to Update Items in A Dictionary in Python

Updating items in a dictionary works in a similar way to adding items to a dictionary.

When you know you want to update one existing key's value, use the following general syntax you saw in the previous section:

To update a dictionary, you can also use the built-in update() method.

This method is particularly helpful when you want to update more than one value inside a dictionary at the same time.

Say you want to update the name and age key in my_dictionary , and add a new key, occupation :

The update() method takes a tuple of key-value pairs.

The keys that already existed were updated with the new values that were assigned, and a new key-value pair was added.

The update() method is also useful when you want to add the contents of one dictionary into another.

Say you have one dictionary, numbers , and a second dictionary, more_numbers .

If you want to merge the contents of more_numbers with the contents of numbers , use the update() method.

All the key-value pairs contained in more_numbers will be added to the end of the numbers dictionary.

How to Delete Items from A Dictionary in Python

One of the ways to delete a specific key and its associated value from a dictionary is by using the del keyword.

The syntax to do so is the following:

For example, this is how you would delete the location key from the my_information dictionary:

If you want to remove a key, but would also like to save that removed value, use the built-in pop() method.

The pop() method removes but also returns the key you specify. This way, you can store the removed value in a variable for later use or retrieval.

You pass the key you want to remove as an argument to the method.

Here is the general syntax to do that:

To remove the location key from the example above, but this time using the pop() method and saving the value associated with the key to a variable, do the following:

If you specify a key that does not exist in the dictionary you will get a KeyError error message:

A way around this is to pass a second argument to the pop() method.

By including the second argument there would be no error. Instead, there would be a silent fail if the key didn't exist, and the dictionary would remain unchanged.

The pop() method removes a specific key and its associated value – but what if you only want to delete the last key-value pair from a dictionary?

For that, use the built-in popitem() method instead.

This is general syntax for the popitem() method:

The popitem() method takes no arguments, but removes and returns the last key-value pair from a dictionary.

Lastly, if you want to delete all key-value pairs from a dictionary, use the built-in clear() method.

Using this method will leave you with an empty dictionary.

And there you have it! You now know the basics of dictionaries in Python.

I hope you found this article useful.

To learn more about the Python programming language, check out freeCodeCamp's Scientific Computing with Python Certification .

You'll start from the basics and learn in an interacitve and beginner-friendly way. You'll also build five projects at the end to put into practice and help reinforce what you've learned.

Thanks for reading and happy coding!

Read more posts .

If this article was helpful, share it .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Assign a dictionary Key or Value to variable in Python

avatar

Last updated: Feb 21, 2023 Reading time · 4 min

banner

# Table of Contents

  • Assign a dictionary value to a Variable in Python
  • Assign dictionary key-value pairs to variables in Python
  • Assign dictionary key-value pairs to variables using exec()

# Assign a dictionary value to a Variable in Python

Use bracket notation to assign a dictionary value to a variable, e.g. first = my_dict['first_name'] .

The left-hand side of the assignment is the variable's name and the right-hand side is the value.

assign dictionary value to variable

The first example uses square brackets to access a dictionary key and assigns the corresponding value to a variable.

If you need to access the dictionary value using an index , use the dict.values() method.

The dict.values method returns a new view of the dictionary's values.

We had to use the list() class to convert the view object to a list because view objects are not subscriptable (cannot be accessed at an index).

You can use the same approach if you have the key stored in a variable.

If you try to access a dictionary key that doesn't exist using square brackets, you'd get a KeyError .

On the other hand, the dict.get() method returns None for non-existent keys by default.

The dict.get method returns the value for the given key if the key is in the dictionary, otherwise a default value is returned.

The method takes the following 2 parameters:

If a value for the default parameter is not provided, it defaults to None , so the get() method never raises a KeyError .

If you need to assign the key-value pairs of a dictionary to variables, update the locals() dictionary.

# Assign dictionary key-value pairs to variables in Python

Update the locals() dictionary to assign the key-value pairs of a dictionary to variables.

assign dictionary key value pairs to variables

The first example uses the locals() dictionary to assign the key-value pairs of a dictionary to local variables.

The locals() function returns a dictionary that contains the current scope's local variables.

The dict.update method updates the dictionary with the key-value pairs from the provided value.

You can access the variables directly after calling the dict.update() method.

The SimpleNamespace class can be initialized with keyword arguments.

The keys of the dictionary are accessible as attributes on the namespace object.

Alternatively, you can use the exec() function.

# Assign dictionary key-value pairs to variables using exec()

This is a three-step process:

  • Iterate over the dictionary's items.
  • Use the exec() function to assign each key-value pair to a variable.
  • The exec() function supports dynamic execution of Python code.

assign dictionary key value pairs to variables using exec

The dict.items method returns a new view of the dictionary's items ((key, value) pairs).

On each iteration, we use the exec() function to assign the current key-value pair to a variable.

The exec function supports dynamic execution of Python code.

The function takes a string, parses it as a suite of Python statements and runs the code.

Which approach you pick is a matter of personal preference. I'd go with the SimpleNamespace class to avoid any linting errors for trying to access undefined variables.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • Check if all values in a Dictionary are equal in Python
  • How to Replace values in a Dictionary in Python
  • Get multiple values from a Dictionary in Python
  • Get random Key and Value from a Dictionary in Python
  • Join the Keys or Values of Dictionary into String in Python
  • Multiply the Values in a Dictionary in Python
  • Print specific key-value pairs of a dictionary in Python
  • How to set all Dictionary values to 0 in Python
  • Sum all values in a Dictionary or List of Dicts in Python
  • Swap the keys and values in a Dictionary in Python

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2023 Borislav Hadzhiev

Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python dictionary keys() method.

❮ Dictionary Methods

Return the keys:

Definition and Usage

The keys() method returns a view object. The view object contains the keys of the dictionary, as a list.

The view object will reflect any changes done to the dictionary, see example below.

Parameter Values

No parameters

More Examples

When an item is added in the dictionary, the view object also gets updated:

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

  • Free Python 3 Tutorial
  • Control Flow
  • Exception Handling
  • Python Programs
  • Python Projects
  • Python Interview Questions
  • Python Database
  • Data Science With Python
  • Machine Learning with Python

python assign keys to dictionary

  • Explore Our Geeks Community
  • Python | Find keys with duplicate values in dictionary
  • Python | Get dictionary keys as a list
  • Python program to find the highest 3 values in a dictionary
  • Python | Difference in keys of two dictionaries
  • Python | Convert dictionary to list of tuples
  • Python | Convert a set into dictionary
  • Python | Convert byteString key:value pair of dictionary to String
  • Python | Get key with maximum value in Dictionary
  • Python program to find the sum of all items in a dictionary
  • Python program to Swap Keys and Values in Dictionary
  • Python - Create a dictionary using list with none values
  • Python | Filter the negative values from given dictionary
  • Python | Sum list of dictionaries with same key
  • Python | Split dictionary keys and values into separate lists
  • Python | Initialize a dictionary with only keys from a list
  • Python | Type conversion in dictionary values
  • Python - Update values of a list of dictionaries
  • Python program to convert Dict of list to CSV
  • Python - Accessing Items in Lists Within Dictionary

Add a key:value pair to dictionary in Python

Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. While using Dictionary, sometimes, we need to add or modify the key/value inside the dictionary. Let’s see how to add a key:value pair to dictionary in Python. 

Code #1: Using Subscript notation This method will create a new key:value pair on a dictionary by assigning a value to that key. 

Current Dict is: {‘key2’: ‘for’, ‘key1’: ‘geeks’} Updated Dict is: {‘key3’: ‘Geeks’, ‘key5’: ‘portal’, ‘key6’: ‘Computer’, ‘key4’: ‘is’, ‘key1’: ‘geeks’, ‘key2’: ‘for’}

Time Complexity: O(1) Auxiliary Space: O(1)

Code #2: Using update() method 

Current Dict is: {‘key2’: ‘for’, ‘key1’: ‘geeks’} {‘newkey1’: ‘portal’, ‘key4’: ‘is’, ‘key2’: ‘for’, ‘key1’: ‘geeks’, ‘key5’: ‘fabulous’, ‘key3’: ‘geeks’}

Code #3: Taking Key:value as input 

Time Complexity: O(1) Auxiliary Space: O(n)

Code #4: Using a dictionary comprehension 

For example, you can create a new dictionary that adds a key:value pair to an existing dictionary like this:

This creates a new dictionary called updated_dict that contains all the key:value pairs from existing_dict, as well as the new key:value pair ‘key3’: ‘value3’.

Time Complexity: O(n) Auxiliary Space: O(n)

Please Login to comment...

  • Python dictionary-programs
  • python-dict
  • pkonline2002

Improve your Coding Skills with Practice

 alt=

IMAGES

  1. Python: Add Key:Value Pair to Dictionary • datagy

    python assign keys to dictionary

  2. Python

    python assign keys to dictionary

  3. How to Add Items to a Python Dictionary?

    python assign keys to dictionary

  4. Python

    python assign keys to dictionary

  5. 81+ How To Append To Dictionary Python Viral

    python assign keys to dictionary

  6. Python Dictionary Keys

    python assign keys to dictionary

VIDEO

  1. Python Dictionary Keys

  2. How To Convert Dictionary To List In Python #python

  3. #dictionary #keys #values #python #_computer_code #youtubeshorts

  4. Super Useful In Python Dictionary #programming #python #coding

  5. Python: Dictionary and Sets

  6. Python Basics Part 13: Dictionaries

COMMENTS

  1. python

    You create a new key/value pair on a dictionary by assigning a value to that key d = {'key': 'value'} print (d) # {'key': 'value'} d ['mynewkey'] = 'mynewvalue' print (d) # {'key': 'value', 'mynewkey': 'mynewvalue'} If the key doesn't exist, it's added and points to that value. If it exists, the current value it points to is overwritten. Share

  2. Python

    This method will create a new key\value pair on a dictionary by assigning a value to that key. If the key doesn't exist, it will be added and will point to that value. If the key exists, the current value it points to will be overwritten. Python3 dict = {'key1': 'geeks', 'key2': 'fill_me'} print("Current Dict is:", dict) dict['key2'] = 'for'

  3. Python: How to Add Keys to a Dictionary

    In Python, we can add multiple key-value pairs to an existing dictionary. This is achieved by using the update () method. This method takes an argument of type dict or any iterable that has the length of two - like ( (key1, value1),), and updates the dictionary with new key-value pairs.

  4. Dictionaries in Python

    Dictionaries in Python - Real Python In this Python dictionaries tutorial, you'll cover the basic characteristics and learn how to access and manage dictionary data. Once you have finished this tutorial, you should have a good sense of when a dictionary is the appropriate data type to use, and how to do so. Start Here Learn Python

  5. How To Add to a Dictionary in Python

    You can use the = assignment operator to add a new key to a dictionary: dict[key] = value If a key already exists in the dictionary, then the assignment operator updates, or overwrites, the value. The following example demonstrates how to create a new dictionary and then use the assignment operator = to update a value and add key-value pairs:

  6. Effortlessly Add Keys to Python Dictionaries: A Complete Guide

    Add keys to dictionary if not exists. To add keys to a dictionary only if they don't already exist, you can use the setdefault() method of the dictionary. This method sets a key to a default value if the key is not already in the dictionary. Here's an example:

  7. How to Add a Key To a Dictionary in Python

    Using Subscript Notation ( [ ] Operator) The subscript notation is defined as square brackets [], and it's used to access the elements of the list or set of a dictionary.. Together with [] and = operators, you can also assign a key-value pair to an existing dictionary object.. Code. The following code shows how to add a new key to a dictionary object. mydict = {"existingkey": "value"} print ...

  8. Python Dictionary (With Examples)

    We can add an item to the dictionary by assigning a value to a new key (that does not exist in the dictionary). For example, country_capitals = { "United States": "Washington D.C.", "Italy": "Naples" } # add an item with "Germany" as key and "Berlin" as its value country_capitals ["Germany"] = "Berlin" print(country_capitals) Run Code

  9. Python: Add Key:Value Pair to Dictionary • datagy

    The easiest way to add an item to a Python dictionary is simply to assign a value to a new key. Python dictionaries don't have a method by which to append a new key:value pair. Because of this, direct assignment is the primary way of adding new items to a dictionary. ... Python: Remove Key from Dictionary (4 Different Ways) Merge Python ...

  10. Multiple assignments into a python dictionary

    76 Is it possible to assign values to more than one keys of a dictionary in a more concise way than the one below? I mean, let d be a dictionary initialized as below: d= {'a':1,'b':2,'c':3} To assign values to multiple keys I need to do this: d ['a']=10 d ['b']=200 d ['c']=30 Can I achieve same with something like this: d ['a','b','c']=10,200,30

  11. How to add values to dictionary in Python

    After defining a dictionary we can index through it using a key and assign a value to it to make a key-value pair. Python3 Output: {0: 'Carrot', 1: 'Raddish', 2: 'Brinjal', 3: 'Potato'} But what if a key already exists in it? Python3 veg_dict [0] = 'Tomato' print(veg_dict) Output: {0: 'Tomato', 1: 'Raddish', 2: 'Brinjal', 3: 'Potato'}

  12. Create a Dictionary in Python

    A dictionary in Python is made up of key-value pairs. In the two sections that follow you will see two ways of creating a dictionary. The first way is by using a set of curly braces, {}, and the second way is by using the built-in dict () function. How to Create An Empty Dictionary in Python

  13. How do I assign a dictionary value to a variable in Python?

    18 I'm an amateur when it comes to programming, but I'm trying my hand at Python. Basically what I want to be able to do is use math on a dictionary value. The only way I could think to do it would be to assign a dictionary value to a variable, then assign the new value to the dictionary. Something like this:

  14. Assign a dictionary Key or Value to variable in Python

    Assign dictionary key-value pairs to variables using exec () # Assign a dictionary value to a Variable in Python Use bracket notation to assign a dictionary value to a variable, e.g. first = my_dict ['first_name']. The left-hand side of the assignment is the variable's name and the right-hand side is the value. main.py

  15. Python Dictionaries

    Dictionary Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered*, changeable and do not allow duplicates. As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered. Dictionaries are written with curly brackets, and have keys and values:

  16. Python

    Method #1 : Using dict () + zip () The combination of above methods can be used to perform this task. In this, we allot the list values to already constructed mesh and zip () helps in mapping values as per list index. Python3 test_dict = {'gfg': '', 'is': '', 'best': ''} test_list = ['A', 'B', 'C']

  17. python

    4 If python >= 3.6, then use zip () + dict (), if < 3.6, looks dict is un-ordered, so I don't know. test.py: categories = {'player_name': None, 'player_id': None, 'season': None} L = ['Player 1', 'player_1', '2020'] print (dict (zip (categories, L))) Results: $ python3 test.py {'player_name': 'Player 1', 'player_id': 'player_1', 'season': '2020'}

  18. python

    101 In Python, I need a dictionary object which looks like: {'a': 10, 'b': 20, 'c': 10, 'd': 10, 'e': 20} I've been able to get this successfully by combining the dict.update () and dict.fromkeys () functions like so: myDict = {} myDict.update (dict.fromkeys ( ['a', 'c', 'd'], 10)) myDict.update (dict.fromkeys ( ['b', 'e'], 20))

  19. Python Dictionary keys() Method

    Python Variables Variable Names Assign Multiple Values Output Variables Global ... Python Dictionary keys() Method Dictionary Methods. Example. Return the keys: ... The keys() method returns a view object. The view object contains the keys of the dictionary, as a list. The view object will reflect any changes done to the dictionary, see example ...

  20. If we use the python's dictionary data collection and we assign a

    Python dictionary: are keys() and values() always the same order? 0 Passing dictionary in args of python. 0 ... Automatically Unpack and Assign, Keys to Values from a Python Dictionary. 2 extract items from several ordered dictionaries stored in one dict object. 33 ...

  21. Python

    Sometimes, while working with Python dictionaries, we can have a problem in which we need to assign list elements as a new key in dictionary. This task can occur in web development domain. Lets discuss certain ways in which this task can be performed.

  22. Add a key:value pair to dictionary in Python

    Code #1: Using Subscript notation This method will create a new key:value pair on a dictionary by assigning a value to that key. Python3 dict = {'key1':'geeks', 'key2':'for'} print("Current Dict is: ", dict) dict['key3'] = 'Geeks' dict['key4'] = 'is' dict['key5'] = 'portal' dict['key6'] = 'Computer' print("Updated Dict is: ", dict) Output: