Python: How to Add Key to a Dictionary

python_tutorials

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 referencing a dictionary’s index with a new key and assigning a value. For example, we add a new key-value pair like this:

snacks['chocolate'] = 5

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 few common ways to do so.

Add Key with Value

We can add a new

 

 

To finish reading, please visit source site