Create a Dictionary in Python

Pycharm Visual Studio Code

In Python, a dictionary is a data structure that stores a collection of key-value pairs. Each key in a dictionary must be unique. Here's an example of how you can create a dictionary:

# Creating an empty dictionary
empty_dict = {}

# Creating a dictionary with some key-value pairs
my_dict = {
    "name": "John Doe",
    "age": 30,
    "city": "New York"
}

# Adding a new key-value pair
my_dict["occupation"] = "Engineer"

# Accessing values in the dictionary
name = my_dict["name"]
age = my_dict["age"]

# Modifying a value
my_dict["age"] = 31

# Removing a key-value pair
del my_dict["city"]

# Checking if a key exists
if "name" in my_dict:
    print("Key 'name' exists in the dictionary.")

# Getting all keys and values
keys = my_dict.keys()
values = my_dict.values()

# Iterating through keys and values
for key, value in my_dict.items():
    print(f"{key}: {value}")

An empty dictionary is created using curly braces {}.

A dictionary called my_dict is created with three key-value pairs: "name", "age", and "city".

You can add new key-value pairs using square brackets and assign a value to the desired key.

Values in a dictionary can be accessed by providing the corresponding key in square brackets.

You can modify the value associated with a key by reassigning a new value to it.

To remove a key-value pair, you can use the del statement followed by the dictionary and the key.

To check if a key exists in a dictionary, you can use the in keyword.

keys() and values() methods can be used to get all keys and values, respectively.

The items() method allows you to iterate through both keys and values together.

Keep in mind that dictionaries in Python are unordered, meaning the order of elements may not be preserved.

Comments
Loading...
Sorry! No comment found:(

There is no comment to show for this.

Leave your comment
Tested Versions
  • Python 3.8