Python Dictionary with Examples


A dictionary in Python is a collection of key-value pairs. Each key is unique and is used to access the corresponding value. Dictionaries are mutable, meaning they can be changed after creation, and they are unordered, meaning the items do not have a defined order.

Note: As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

Usage and Purpose

Dictionaries are used to store data values like a map. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type, typically strings or numbers.

Example and Operations

1. Creating a Dictionary

# Creating a dictionary
person = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

2. Accessing Values

# Accessing values
print(person["name"])  # Output: John
print(person.get("age"))  # Output: 30

3. Adding and Updating Items

# Adding a new key-value pair
person["email"] = "[email protected]"

# Updating an existing key-value pair
person["age"] = 31

4. Removing Items

# Removing a key-value pair using pop
person.pop("city")

# Removing the last inserted key-value pair using popitem
person.popitem()

# Removing a key-value pair using del
del person["email"]

5. Iterating through a Dictionary

# Iterating through keys
for key in person:
    print(key)

# Iterating through values
for value in person.values():
    print(value)

# Iterating through key-value pairs
for key, value in person.items():
    print(f"{key}: {value}")

6. Checking if a Key Exists

# Checking if a key exists
if "name" in person:
    print("Name is present")

7. Dictionary Methods

# Getting the number of items
print(len(person))

# Clearing all items
person.clear()

# Copying a dictionary
person_copy = person.copy()

Summary

Dictionaries are highly efficient for lookups, insertions, and deletions, making them a versatile and powerful data structure in Python.

References

  1. Dictionaries – Python
  2. Java: Difference between HashMap and Hashtable

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.