• Python Home
  • Documentation
  • Developer's Guide
  • Random Issue
  • Issues with patch
  • Easy issues

Google

  • Lost your login?
  • Committer List
  • Tracker Documentation
  • Tracker Development
  • Report Tracker Problem

python dictionary assignment not working

This issue tracker has been migrated to GitHub , and is currently read-only . For more information, see the GitHub FAQs in the Python's Developer Guide.

This issue has been migrated to GitHub: https://github.com/python/cpython/issues/84819

Created on 2020-05-16 05:02 by jacob.underwood , last changed 2022-04-11 14:59 by admin . This issue is now closed .

Add new keys to a dictionary in Python

python dictionary assignment not working

.css-13lojzj{position:absolute;padding-right:0.25rem;margin-left:-1.25rem;left:0;height:100%;display:-webkit-inline-box;display:-webkit-inline-flex;display:-ms-inline-flexbox;display:inline-flex;-webkit-align-items:center;-webkit-box-align:center;-ms-flex-align:center;align-items:center;display:none;} .css-b94zdx{width:1rem;height:1rem;} The Problem

How can I add new keys to a dictionary in Python?

The Solution

Python provides a few different ways to add new key-value pairs to an existing dictionary. The simplest way is to assign a value to a new key using Python’s indexing/square brackets syntax:

This same syntax can be used to update existing key-value pairs:

To add and update multiple key-value pairs at once, we can use Python’s dict.update() method:

You can also use the dictionary comprehension and dictionary constructor together to add or update the key-value pairs:

As of Python 3.9 , we can use the update operator ( |= ) instead of the update() method:

Related Answers

  • Access environment variables in Python
  • Accessing the Index in a `for` Loop in Python
  • Access the index of a for loop
  • Add a new column to a DataFrame in Python Pandas
  • Append vs. extend in Python
  • Change the size of figures drawn with Matplotlib in Python
  • Check for NaN values in Python
  • Check if a dictionary contains a key in Python
  • Check if a list is empty in Python
  • Check if a string is empty in Python
  • Concatenate two lists in Python
  • Convert a list to a string in Python
  • Convert a string to bytes in Python
  • Convert an integer to a string in Python
  • Convert bytes to a string in Python
  • Convert a string containing a date into datetime in Python
  • Copy files in Python
  • Count occurrences of item in Python list
  • Declare an array in Python
  • Define a two-dimensional array in Python
  • Delete a column from a DataFrame in Python Pandas
  • Delete a file or folder in Python
  • Delete element from a dictionary in Python
  • Determine the type of a Python variable
  • Difference between `@staticmethod` and `@classmethod` function decorators in Python
  • Extract a substring from a string in Python
  • Fastest way to check if a list contains an item in Python
  • How to manage feature flags without making performance worse
  • Find all files in a directory with a given extension using Python
  • Find item in list in Python
  • Find the current directory and executed file's directory in Python
  • Generate random integers within a range in Python
  • Get key by value in dictionary Python
  • Get the current script file's full directory path in Python
  • Get the current time in Python
  • Get the last element of a list in Python
  • Get the length of a list in Python
  • Get unique values from a list in Python
  • How do I append one string to another in Python?
  • How do I parse a string to a float or int?
  • How do I remove a trailing newline from a string in Python
  • Import files from a different folder in Python
  • What does `if __name__ == "__main__":` do?
  • Indentation errors in Python
  • Install a specific version of a Python package using PIP
  • Install Python packages from a local package index
  • Invalid literal for int error in Python
  • Iterate over rows in a Pandas DataFrame in Python
  • Limit floats to two decimal points in Python
  • Is There a List of pytz Timezones?
  • Logical AND (&&) in Python
  • Lowercase a string in Python
  • Making a list out of a list of lists in Python?
  • Measure elapsed time in Python
  • Pandas DataFrame row count in Python
  • Print multiple times without newlines or spaces in Python
  • Sort a dictionary by value in Python
  • Python equivalent of a ternary operator: if-then-else in one line
  • Iterate over a dictionary in Python
  • List files in a directory using Python
  • How Do I Merge Two Dictionaries in a Single Expression (Take Union of Dictionaries)?
  • How Can I Safely Create a Nested Directory?
  • Python slice notation
  • Does Python Have a Ternary Conditional Operator?
  • What Does the `yield` Keyword in Python Do?
  • Raise an exception in Python
  • Read a file line by line into a list Python
  • Remove element from a list by index in Python
  • Remove whitespace from a string in Python
  • Rename columns in a Python Pandas DataFrame
  • Running External Programs in Python
  • Save a Matplotlib plot to a file in Python
  • Select multiple columns in Python Pandas
  • Select rows from a Python Pandas DataFrame based on column values
  • Slicing in Python
  • Split statements across multiple lines in Python code
  • TypeError 'str' Object Does Not Support Item Assignment
  • `super()` and `__init__()` in Python
  • Switch-case statement equivalents in Python
  • Time delay in Python
  • UnboundLocalError Local Variable 'index' Referenced Before Assignment
  • Upgrade specific `pip` packages in Python
  • Use global variables in Python functions
  • What are Python Metaclasses?
  • Write one or more lines to a file in Python

A better experience for your users. An easier life for your developers.

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

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

IMAGES

  1. Python Dictionary setdefault

    python dictionary assignment not working

  2. [Solved] Updating a python dictionary while adding to

    python dictionary assignment not working

  3. How to Add Items to a Python Dictionary?

    python dictionary assignment not working

  4. 4 Easy Techniques to Check if Key Exists in a Python Dictionary

    python dictionary assignment not working

  5. Python Dictionary Index

    python dictionary assignment not working

  6. Remove All Keys From Python Dictionary

    python dictionary assignment not working

VIDEO

  1. python dictionary 1080p

  2. How to Assign Multiple Values to Variables in Python

  3. Python Week 5 Graded Assignment(IITM)

  4. Python circular reference

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

  6. This Works On Python Dictionaries?? #python #programming #coding

COMMENTS

  1. The Ultimate Guide to Choosing the Right Python Developer Online Course

    Are you looking to become a Python developer? With its versatility and widespread use in the tech industry, Python has become one of the most popular programming languages today. One factor to consider is whether you prefer self-paced learn...

  2. How to Use Turnitin Assignment Checker to Ensure Academic Integrity

    In the academic world, it is essential to maintain academic integrity and ensure that all assignments are original. To help with this, many universities and schools use Turnitin Assignment Checker. This tool is used to detect plagiarism in ...

  3. How to Interpret the Results of Turnitin Assignment Checker Reports

    As an educator or student, you understand the importance of submitting original work. However, with the ease of accessing information on the internet, it can be challenging to ensure that your content is plagiarism-free. That’s where Turnit...

  4. Python nested dictionary assignment not working

    Python nested dictionary assignment not working · You need to show a self-contained example demonstrating the problem. · Please post the

  5. Issue 40639: Strange behavior in changing nested dictionaries

    ... not. Python never copies data structures unless you explicitly tell it to, and specifically assignment does not make copies either. So when

  6. Trying to assign values to keys in dictionary gives type error

    TypeError: 'type' object does not support item assignment ... How to keep keys/values in same order as declared? 412 · Python dictionary: are keys

  7. How To Add to a Dictionary in Python

    If a key already exists in the dictionary, then the assignment operator updates, or overwrites, the value. The following example demonstrates

  8. Dictionaries in Python

    ... assign the result to a variable. Your example does work. If you print hawk, you'll see that it has been updated :D. MIGUEL ANGEL HERNANDEZ • 4 years ago. Geir

  9. Python

    Sometimes, while working with python dictionaries, we can have a problem in which we need to initialize dictionary keys with values. We save

  10. Python Dictionary Comprehension Tutorial

    ... not the possible index of the word. Python dictionaries work with the same concept, the word whose meaning you are looking for is the key, and the meaning

  11. Add new keys to a dictionary in Python

    The Problem How can I add new keys to a dictionary in Python? The Solution Python provides a few different ways to add new key-value pairs

  12. Nested dictionaries in Python

    So here I will show the result of my fight with these problems. If you have worked with nested dictionaries you can skip “What is a nested

  13. Create a Dictionary in Python

    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

  14. Python Dictionary (With Examples)

    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