Dictionaries in Python are essential data structures that allow for the storage and manipulation of data in key-value pairs. A range of numbers indexes lists, while keys index dictionaries. Which can be any immutable type. This makes dictionaries incredibly powerful and flexible for various programming tasks.
In this tutorial, we will explore the various aspects of dictionaries in Python, from their characteristics and creation to accessing and updating built-in functions and methods. After reading this article, you will understand how to effectively use dictionaries in your Python programs.
What is a Dictionary in Python?
In Python, a dictionary is a mutable, unordered collection of items where each item is stored in a key-value pair. Dictionaries are commonly used to store data in a way that allows quick access and modification. Here’s a brief overview of dictionaries in Python language.
Characteristics of Python Dictionaries
Key-Value Pairs: In the Dictionary, each item is a pair consisting of a key and a value. Keys must be unique and immutable(e.g., strings, numbers, or tuples), while values of any data type can be duplicated.
Unordered: Python dictionaries are unordered collections, which means that items do not have a defined order and cannot be accessed by an index.
Mutable: Dictionaries are mutable, meaning you can add, remove or change items after creating the dictionary.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
Creating a Dictionary
Creating a Python dictionary is very simple. The required key and value pairs are within curly brackets and separated by the key-value pair.
The following program creates a dictionary in Python language.
We can also update the dictionary in Python language in Python. We can add a new entry or modify the existing entry and add multiple values to a single key.
The following program demonstrates updating the dictionary values in Python.
Program
#creating an empty dictionary
my_dict={}
print(my_dict)
#adding elements to the dictionary one at a time
my_dict[1]="Voldemort"
my_dict[2]="Harry"
my_dict[3]="RajKumar"
print(my_dict)
#modifying existing entry
my_dict[2]="Apple Laptop"
print(my_dict)
#adding multiple values to a single key
my_dict[4]="Banana,Cherry,Kiwi"
print(my_dict)
#adding nested key values
my_dict[5]={'Nested' :{'1' : 'Hero Vired', '2': 'Academy'}}
print(my_dict)
We can also delete the dictionaries in Python language. Let’s look at “ how we can either delete the dictionary entirely or remove individual entries”.
To remove an entire dictionary. We can use the ‘del’ keyword in Python language.
The following program demonstrates “del keyword in Python”.
You can iterate through a dictionary’s keys, values, or key-value pairs in Python language.
The following program Iterate the dictionary using the loop.
Program
# Iterating through keys
my_dict = {
"name": "Alice",
"age": 25,
"city": "New York"
}
for key in my_dict:
print(key, my_dict[key])
# Iterating through values
for value in my_dict.values():
print(value)
# Iterating through key-value pairs
for key, value in my_dict.items():
print(key, value)
Output
name Alice
age 25
city New York
Alice
25
New York
name Alice
age 25
city New York<strong style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif;"> </strong>
Properties of Python Dictionary Keys
Let’s see the properties of Python dictionary kes summarized in single points.
Immutability: Python dictionary must be immutable.
Uniqueness: Python keys within a dictionary must be unique
Hashability: Python keys must be hashable.
Comparable: Python keys must support equality comparison
Built-in Python Dictionary Functions & Methods
There are some built-in methods and functions in Python.
Functions
Description
cmp(dict1, dict2)
This function compares the items of both dictionaries and returns true if the value of the first dictionary. Suppose the first value is greater than It will return true otherwise. It will return false.
len(dict)
It gives the total number of items in the dictionary
str(dict)
This function produces a string representation of the dictionary
all(dict)
This function returns true if all the keys in the dictionary are true.
any(dict)
This function returns true if any key in the dictionary is true.
sorted(dict)
It returns a new sorted list of keys in a dictionary
dict.clear()
This method removes all elements from the dictionary.
dict.copy()
This function returns a copy of the dictionary
dict.pop()
This function removes an element from the specified key.
dict.get()
This function is used to get the value of the specified key
dict.fromkeys()
This function creates a new dictionary with keys from seq and values set to value.
dict.items()
This function returns the list of dictionary tuple pairs.
dict.update(dict2)
This adds the dict2 key-value pairs to dict
dict.has_key()
This function returns true if the specified key is present in the dictionary else false.
Conclusion
In this article, we learned about the dictionaries in Python. It is a versatile and powerful data structure tool that efficiently stores and manages data using key-value pairs. It offers several advantages, such as fast lookups, flexibility in data types for keys and values, and ease of use with various built-in methods. Mastering Python dictionaries enhances your capability to handle data efficiently, perform rapid searches, and develop sophisticated applications. There are also some built-in methods and functionalities, such as ‘get()’, ‘update()’, ‘items()’, ‘keys()’ and values()’.
FAQs
What is a dictionary in Python?
A dictionary in Python is an unordered collection of items. Each item is stored as a key-value pair where each key is unique and maps to a value.
Can dictionary keys be of any data type?
Dictionary keys must be of a hashable type, typically including immutable type like strings, numbers, and tuples. Lists and other dictionaries cannot be used as keys.
What are the rules of a dictionary in Python?
The syntax of the python dictionary begins with left curly braces({), ends with the right curly brace(}), and contains zero or more key: value items separated by commas, (,). The key is separated from the value by a colon(:).
How do I create a dictionary from two lists?
A dictionary can be created from two lists using the ‘zip()’ function. This function pairs elements from both lists and then converts them into key-value pairs.
Can a dictionary have duplicate values?
Yes, A dictionary can have duplicate values but not duplicate keys.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.