Mastering The Dictionary Data Type: A Comprehensive Guide

Python Dictionary
Python Dictionary

Learn everything about Python dictionaries in this comprehensive guide. From key-value pairs to dictionary comprehension, master this essential Python data type today!

Check out our full Python guide here. : Learn From KSR Datavizon | Explore and Read Our Blogs Written By Our Industry Expert

Key Characteristics of a Python Dictionary

1. Key-Value Pairs:

  • A dictionary stores data as key-value pairs. The keys must be unique and immutable (like strings, numbers, or tuples), while the values can be of any data type and can repeat.

2. Mutable:

  • You can change or update the values associated with a key, add new key-value pairs, or remove existing ones.

3. Efficient Lookups:

  • Accessing a value via a key is a constant time operation (O(1)), making dictionaries very efficient for lookups.

Python Dictionary Creation

Dictionaries are created by using the curly braces {} or the dict() function.

Syntax: d = {key_01:value_01, key_02:value_02, …., key_N: value_N}

Empty python dictionary

d = {}
print(d) # Output: {}
print(type(d)) # Output: <class ‘dict’>

Python Dictionary with key, value pairs

d = {1:"Ramesh", 2:"Arjun", 3:"Karthik"}
print(d) 

# Output:
{1:"Ramesh", 2:"Arjun", 3:"Karthik"}

How to Add Items to a Dictionary

Syntax: d[key] = value

# Creating an empty dictionary
d = {}

# Adding entries to the dictionary
d[100] = "karthik"
d[200] = "ravi"
d[300] = "shiva"

print(d)  # Output: {100: 'karthik', 200: 'ravi', 300: 'shiva'}

Accessing Values in a Dictionary

  • Keys are used to access values in a dictionary.
  • The key acts as the identifier for the associated value.
# Dictionary with key-value pairs
student = {
    "name": "John",
    "age": 21,
    "course": "Computer Science"
}

# Accessing values using keys
print(student["name"])    # Output: John
print(student["age"])     # Output: 21
print(student["course"])  # Output: Computer Science

If you try to access a key which doesn’t exist, Python raises a KeyError.

Common Dictionary Operations

OperationDescriptionExample
Access a value by keyRetrieve the value associated with a specific keystudent[‘name’] → ‘John’
Add or update key-valueAdd a new key-value pair or update an existing valuestudent[‘age’] = 22
Remove an itemRemove a key-value pair using del or the pop() methodstudent.pop(‘age’)
Check if key existsCheck if a key is present in the dictionary using in‘name’ in student → True
Get all keysRetrieve a list of all keys in the dictionarystudent.keys() → [‘name’, ‘age’]
Get all valuesRetrieve a list of all values in the dictionarystudent.values() → [‘John’, 21]
Get key-value pairsRetrieve a list of tuples containing all key-value pairsstudent.items() → [(‘name’, ‘John’)]
FunctionDescriptionExampleOutput
len(dict)Returns the number of key-value pairs in the dictionary.len({‘name’: ‘Alice’, ‘age’: 25})2
min(dict)Returns the smallest key in the dictionary (based on sorting).min({‘b’: 2, ‘a’: 1, ‘c’: 3})‘a’
max(dict)Returns the largest key in the dictionary (based on sorting).max({‘b’: 2, ‘a’: 1, ‘c’: 3})‘c’
sorted(dict)Returns a sorted list of keys from the dictionary.sorted({‘b’: 2, ‘a’: 1, ‘c’: 3})[‘a’, ‘b’, ‘c’]
reversed(dict)Not applicable: Cannot reverse a dictionary as it is unordered.N/AN/A

Note: The reversed() function does not apply to dictionaries because they are unordered collections.

Examples Using All Functions Together

# Creating a dictionary
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}

# len() - Get the number of key-value pairs in the dictionary
print(f"Length of the dictionary: {len(my_dict)}")  # Output: 3

# min() - Get the smallest key in the dictionary
print(f"Smallest key: {min(my_dict)}")  # Output: 'age' (as strings are compared)

# max() - Get the largest key in the dictionary
print(f"Largest key: {max(my_dict)}")  # Output: 'name' (as strings are compared)

# sorted() - Sort the keys and return a list
print(f"Sorted keys: {sorted(my_dict)}")  # Output: ['age', 'city', 'name']

# reversed() - Not applicable, would raise an error if tried.

Removing or Deleting Elements from a Dictionary

  1. Using the del Keyword: remove specific keys from a dictionary using the del statement.
  2. Using the clear() Method: remove all items from the dictionary, effectively clearing it.
# Creating a dictionary
d = {100: 'karthik', 200: 'ravi', 300: 'shiva'}

# Displaying the original dictionary
print("Original Dictionary:", d)  # Output: {100: 'karthik', 200: 'ravi', 300: 'shiva'}

# Removing a specific key-value pair using del
del d[200]
print("After deleting key 200:", d)  # Output: {100: 'karthik', 300: 'shiva'}

# Clearing all items from the dictionary
d.clear()
print("After clearing the dictionary:", d)  # Output: {}

Dictionary Methods

MethodDescriptionExample
dict.get(key)Returns the value of the specified key. If the key does not exist, returns None.student.get(‘age’) → 21
dict.update(dict2)Updates the dictionary with items from another dictionary.student.update({‘age’: 22})
dict.pop(key)Removes and returns the value linked to the specified key.student.pop(‘age’) → 21
dict.clear()Removes all items from the dictionary.student.clear()
dict.keys()Returns a view object of all keys.student.keys() → [‘name’, ‘age’, ‘major’]
dict.values()Returns a view object of all values.student.values() → [‘John’, 21, ‘CS’]
dict.items()Returns a view object of all key-value pairs.student.items() → [(‘name’, ‘John’), (‘age’, 21)]
# Creating a dictionary
student = {
    'name': 'Alice',
    'age': 24,
    'major': 'Physics'
}

# Accessing a value
print(student['name'])  # Output: Alice

# Adding a new key-value pair
student['graduation_year'] = 2024
print(student)  # Output: {'name': 'Alice', 'age': 24, 'major': 'Physics', 'graduation_year': 2024}

# Updating a value
student['age'] = 25
print(student)  # Output: {'name': 'Alice', 'age': 25, 'major': 'Physics', 'graduation_year': 2024}

# Removing a key-value pair
student.pop('major')
print(student)  # Output: {'name': 'Alice', 'age': 25, 'graduation_year': 2024}

# Checking if a key exists
print('age' in student)  # Output: True

# Getting all keys, values, and key-value pairs
print(student.keys())    # Output: dict_keys(['name', 'age', 'graduation_year'])
print(student.values())  # Output: dict_values(['Alice', 25, 2024])
print(student.items())   # Output: dict_items([('name', 'Alice'), ('age', 25), ('graduation_year', 2024)])

Dictionary Comprehension

Dictionary comprehensions offer an best way to construct dictionaries in Python. Comprehensions consist of an expression, followed by a for clause, and can include optional conditionals.

Syntax: d = {key_expression: value_expression for item in iterable if cond}

Example:

# Creating a dictionary of squares
squares = {x: x**2 for x in range(5)}
print(squares)  # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# Creating a dictionary of squares for even numbers only
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
print(even_squares)  # Output: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

Conclusion

Dictionaries are one of Python’s powerful and flexible data structures. They provide efficient access to data through key-value pairs and support a wide range of operations. Their ability to store heterogeneous data and handle dynamic data sizes makes them indispensable for many programming scenarios.

Knowledge Check

Related Article No.4

https://blog.ksrdatavision.com/python/input-and-output-in-python
Data Analytics with Power Bi and Fabric
Could Data Engineer
Data Analytics With Power Bi Fabic
AWS Data Engineering with Snowflake
Azure Data Engineering
Azure & Fabric for Power bi
Full Stack Power Bi
Subscribe to our channel & Don’t miss any update on trending technologies

Kick Start Your Career With Our Data Job

Master Fullstack Power BI – SQL, Power BI, Azure Cloud & Fabric Tools
Master in Data Science With Generative AI Transform Data into Business Solutions
Master Azure Data Engineering – Build Scalable Solutions for Big Data
Master AWS Data Engineering with Snowflake: Build Scalable Data Solutions
Transform Your Productivity With Low Code Technology: Master the Microsoft Power Platform

Social Media channels

► KSR Datavizon Website :- https://www.datavizon.com
► KSR Datavizon LinkedIn :- https://www.linkedin.com/company/datavizon/
► KSR Datavizon You tube :- https://www.youtube.com/c/KSRDatavizon
► KSR Datavizon Twitter :- https://twitter.com/ksrdatavizon
► KSR Datavizon Instagram :- https://www.instagram.com/ksr_datavision
► KSR Datavizon Face book :- https://www.facebook.com/KSRConsultingServices
► KSR Datavizon Playstore :- https://play.google.com/store/apps/details?id=com.datavizon.courses&hl=en-IN
► KSR Datavizon Appstore :- https://apps.apple.com/in/app/ksr-datavizon/id1611034268

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *