How to Create a Dictionary in Python
How to Create a Dictionary in Python
In Python, a dictionary is an unordered collection of data entries, designed to store data in a key-value format, similar to how a map functions. Unlike other data structures that store single items, dictionaries use a pair of items: a key and a value. This makes dictionaries highly efficient for data retrieval and storage tasks.
Complete Python Course with Advance topics:-Click here
What is a Dictionary in Python?
A dictionary contains a key-value pair for each entry, where:
- Key: An immutable and unique identifier (e.g., a string, number, or tuple).
- Value: The data associated with the key (e.g., strings, numbers, lists, or other objects).
Creating a Dictionary
We can create dictionaries in several ways:
1. Using Curly Braces {}
The most common method to create a dictionary is by using curly braces to wrap key-value pairs, separated by commas.
# Initializing a dictionary with elements
dictionary = {1: 'Python', 2: 'Dictionaries', 3: 'Tutorial'}
print("Dictionary created using curly braces:")
print(dictionary)
# Dictionary with keys of different data types
dictionary = {'Website': 'LearnPython', 42: [7, 8, 9, 'Key-Value']}
print("\nDictionary with keys of multiple data types:")
print(dictionary)
Output:
Dictionary created using curly braces:
{1: 'Python', 2: 'Dictionaries', 3: 'Tutorial'}
Dictionary with keys of multiple data types:
{'Website': 'LearnPython', 42: [7, 8, 9, 'Key-Value']}
2. Using the dict()
Constructor
Python’s built-in dict()
method provides another way to create dictionaries.
# Empty dictionary
dictionary = {}
print("Empty dictionary:")
print(dictionary)
# Creating a dictionary using the dict() method
dictionary = dict({1: 'Learn', 2: 'Python', 3: 'Dictionaries'})
print("\nDictionary created using dict():")
print(dictionary)
# Creating dictionary with key-value pairs as tuples
dictionary = dict([(1, 'Key1'), (2, 'Key2'), (3, 'Key3')])
print("\nDictionary created with key-value pair tuples:")
print(dictionary)
Output:
Empty dictionary:
{}
Dictionary created using dict():
{1: 'Learn', 2: 'Python', 3: 'Dictionaries'}
Dictionary created with key-value pair tuples:
{1: 'Key1', 2: 'Key2', 3: 'Key3'}
Adding Elements to a Dictionary
You can add elements to a dictionary in the following ways:
- Using Key Assignment:
dictionary[key] = value
- Using
update()
: Adds new items or updates existing ones.
# Adding elements to a dictionary
dictionary = {}
dictionary[1] = 'Python' # Adding a key-value pair
dictionary[2] = 'Tutorial'
dictionary.update({3: 'Dictionaries'}) # Using update()
print("Dictionary after adding elements:")
print(dictionary)
# Adding a list to a key
dictionary['ListValues'] = [1, 2, 3]
print("\nDictionary after adding a list:")
print(dictionary)
# Adding a nested dictionary
dictionary[4] = {'NestedKey': {'SubKey1': 'Value1', 'SubKey2': 'Value2'}}
print("\nDictionary with a nested key-value pair:")
print(dictionary)
Output:
Dictionary after adding elements:
{1: 'Python', 2: 'Tutorial', 3: 'Dictionaries'}
Dictionary after adding a list:
{1: 'Python', 2: 'Tutorial', 3: 'Dictionaries', 'ListValues': [1, 2, 3]}
Dictionary with a nested key-value pair:
{1: 'Python', 2: 'Tutorial', 3: 'Dictionaries', 'ListValues': [1, 2, 3], 4: {'NestedKey': {'SubKey1': 'Value1', 'SubKey2': 'Value2'}}}
Removing Elements from a Dictionary
There are various ways to remove items from a dictionary:
pop(key)
: Removes a specific key and returns its value.popitem()
: Removes and returns the last added key-value pair.clear()
: Clears the entire dictionary.del
keyword: Deletes specific keys or the entire dictionary.
# Removing elements from a dictionary
dictionary = {1: 'Python', 2: 'Dictionaries', 3: 'Tutorial'}
# Using pop()
dictionary.pop(2)
print("\nAfter removing key 2 using pop():")
print(dictionary)
# Using popitem()
dictionary.popitem()
print("\nAfter removing the last key-value pair using popitem():")
print(dictionary)
# Using clear()
dictionary.clear()
print("\nAfter clearing the dictionary:")
print(dictionary)
# Deleting the dictionary
del dictionary
try:
print(dictionary)
except NameError:
print("\nDictionary has been deleted.")
Output:
After removing key 2 using pop():
{1: 'Python', 3: 'Tutorial'}
After removing the last key-value pair using popitem():
{1: 'Python'}
After clearing the dictionary:
{}
Dictionary has been deleted.
Common Dictionary Methods
Below are some useful dictionary methods:
Method | Description |
---|---|
clear() |
Removes all elements from the dictionary. |
copy() |
Returns a shallow copy of the dictionary. |
fromkeys() |
Creates a new dictionary with specified keys and values. |
get(key) |
Returns the value of a key or a default value if the key doesn’t exist. |
items() |
Returns all key-value pairs as a list of tuples. |
keys() |
Returns a list of all keys in the dictionary. |
values() |
Returns a list of all values in the dictionary. |
pop(key) |
Removes a key and returns its value. |
popitem() |
Removes and returns the last inserted key-value pair. |
update() |
Updates the dictionary with the specified key-value pairs. |
Download New Real Time Projects :-Click here
dictionary in python example
how to create a dictionary in python
python create dictionary from list
how to create a dictionary in python using for loop
how to create a dictionary in python with user input
how to add elements in dictionary in python
dictionary methods in python
how to create a dictionary in python full explanation
how to Create a Dictionary in Python
set in python
list of dictionaries – python
python compiler
how to create a dictionary in python with example
how to create a dictionary in python w3schools
Post Comment