Dictionaries

Dictionaries are another fundamental data structure in Python used for storing collections of items. Unlike lists which use numerical indexes for access, dictionaries use key-value pairs. This makes them ideal for situations where you need to associate data with names or unique identifiers.

Here's a breakdown of dictionaries in Python:

1. Creating Dictionaries:

  • Dictionaries are created using curly braces {} with key-value pairs separated by colons ::

Python
# Simple dictionary
person = {"name": "Alice", "age": 30, "city": "New York"}

# Dictionary with mixed data types
data = {1: "One", 2.5: "Two point five", True: "Boolean value"}

  • Keys must be immutable (like strings, numbers, or tuples). Values can be of any data type.

2. Accessing Elements:

  • You can access elements using their keys within square brackets:

Python
name = person["name"]  # name will be "Alice"

  • Trying to access a non-existent key will result in a KeyError. You can use the get() method to handle missing keys gracefully:

Python
occupation = person.get("occupation", "Unemployed")  # Returns "Unemployed" if "occupation" key is missing

3. Modifying Dictionaries:

  • Dictionaries are mutable, you can change their contents after creation.
  • Assign a new value to an existing key to modify it:

Python
person["age"] = 31  # Updates the age of the person

  • Add new key-value pairs using the assignment operator:

Python
person["occupation"] = "Software Engineer"

  • Remove key-value pairs using the del keyword:

Python
del person["city"]  # Removes the "city" key-value pair

4. Common Dictionary Methods:

  • keys(): Returns a view of all keys in the dictionary.
  • values(): Returns a view of all values in the dictionary.
  • items(): Returns a view of all key-value pairs as tuples.
  • in: Checks if a specific key exists in the dictionary.

5. Looping through Dictionaries:

  • You can iterate over the keys or key-value pairs of a dictionary:

Python
# Looping through keys
for key in person:
  print(key, person[key])

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

Advantages of Dictionaries:

  • Fast lookups: Accessing elements by key is very efficient (average time complexity of O(1)).
  • Flexible keys: Keys can be any immutable data type, allowing for meaningful names or identifiers.
  • Unordered: The order of elements in a dictionary is not guaranteed, which is sometimes desirable.

When to Use Dictionaries:

  • When you need to associate data with unique labels or identifiers.
  • When the order of elements is not important.
  • For representing real-world entities with attributes (like person, product, etc.).

I hope this explanation clarifies dictionaries in Python. Feel free to ask if you'd like to explore specific examples or use cases for dictionaries!

Search
Categories
Read More
Technology
Everything You Need to Know Before Starting with TebTalks
By Mpatswe Francis 2024-09-03 22:02:03 0 2K
Business
Tejinder Singh Bhatia Sukhm – Expert Web Designer with 15 Years of Creative and Technical Excellence
In today’s fast-paced digital world, having a well-designed website is essential for any...
By Bonnie Rose 2024-10-05 06:21:50 0 2K
Technology
Digital Divide
The digital divide refers to the gap between individuals, households, businesses, and geographic...
By ALAGAI AUGUSTEN 2024-07-16 16:59:32 0 2K
Physics
UCE PHYSICS PAPER 1 WAKATA MOCKS 2024
UCE PHYSICS PAPER 1 WAKATA MOCKS 2024
By Landus Mumbere Expedito 2024-08-10 07:19:10 0 3K
Technology
Management Information Systems (MIS)
Management Information Systems (MIS) are integrated systems designed to support management and...
By Business Information Systems (BIS) Course 2024-08-01 16:58:59 0 2K