Introduction to Dictionaries in Python

Introduction to Dictionaries in Python

Definition

A dictionary in Python is a data structure that stores pairs of keys and values. Each key in a dictionary is unique and is used to access its associated value. Dictionaries are highly versatile and are used for various tasks including fast lookups, managing structured data, and establishing associations between keys and values.

Basic Syntax

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

Syntax: 

my_dict = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
}

 Example: 

person_dict = {
    "name": "John",
    "age": 25,
    "city": "New York"
}

 Keys and Values

  • Key: A unique identifier used to access a value in the dictionary. Keys must be immutable types (e.g., strings, numbers, or tuples containing only immutable elements).
  • Value: The data associated with a key. Values can be of any type, including lists, other dictionaries, and custom objects.

Example: 

d = {
    "id": 101,
    "name": "Alice",
    "age": 30,
    "skills": ["Python", "Django", "Machine Learning"]
}

Accessing Values

To access a value in a dictionary, you use the key in square brackets [].

Example: 

d = {
    "name": "Alice",
    "age": 30
}
print(d["name"])  # Outputs 'Alice'
print(d["age"])   # Outputs 30

 Adding or Modifying Elements

You can add a new key-value pair or modify an existing pair using the key.

Example: 

d = {
    "name": "Alice",
    "age": 30
}
# Add a new key-value pair
d["city"] = "Paris"
# Modify an existing value
d["age"] = 31
print(d)  # Outputs {'name': 'Alice', 'age': 31, 'city': 'Paris'}

Removing Elements

To remove elements from a dictionary, you can use the pop() method, the popitem() method, or the del statement.

  • pop(): Removes a key-value pair by specifying the key and returns the associated value.
  • popitem(): Removes and returns the last key-value pair inserted into the dictionary (available since Python 3.7).
  • del: Removes a key-value pair by specifying the key.

Example: 

d = {
    "name": "Alice",
    "age": 30,
    "city": "Paris"
}
# Remove with pop()
value = d.pop("city")
print(value)  # Outputs 'Paris'
print(d)      # Outputs {'name': 'Alice', 'age': 30}
# Remove with popitem()
key_value = d.popitem()
print(key_value)  # Outputs ('age', 30)
print(d)          # Outputs {'name': 'Alice'}
# Remove with del
del d["name"]
print(d)  # Outputs {}

Common Dictionary Methods

  • .keys(): Returns a view object of the dictionary’s keys.
  • .values(): Returns a view object of the dictionary’s values.
  • .items(): Returns a view object of the dictionary’s key-value pairs.
  • .get(): Returns the value for a given key. Returns None if the key does not exist.
  • .setdefault(): Returns the value for a given key. If the key does not exist, it adds the key with a default value.
  • .update(): Updates the dictionary with key-value pairs from another dictionary or iterable of key-value pairs.

Example: 

d = {
    "name": "Alice",
    "age": 30
}
# Get keys
print(d.keys())  # Outputs dict_keys(['name', 'age'])
# Get values
print(d.values())  # Outputs dict_values(['Alice', 30])
# Get items
print(d.items())  # Outputs dict_items([('name', 'Alice'), ('age', 30)])
# Use get()
print(d.get("name"))  # Outputs 'Alice'
print(d.get("city", "Not defined"))  # Outputs 'Not defined'
# Use setdefault()
d.setdefault("city", "Paris")
print(d)  # Outputs {'name': 'Alice', 'age': 30, 'city': 'Paris'}
# Use update()
d.update({"profession": "Engineer", "country": "France"})
print(d)  # Outputs {'name': 'Alice', 'age': 30, 'city': 'Paris', 'profession': 'Engineer', 'country': 'France'}

Applications of Dictionaries

Dictionaries are used for:

  • Storing configurations and settings.
  • Managing in-memory databases.
  • Associating values with unique identifiers.
  • Implementing complex data structures like graphs and trees.

Summary

Dictionaries in Python are versatile data structures for associating unique keys with values. They are mutable, support various operations for adding, removing, and modifying elements, and are crucial for managing structured data and performing quick lookups.

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *