Elements of Dictionaries with Python

Elements of Dictionaries

Structure of Dictionary Elements

A dictionary in Python consists of pairs of keys and values. Each element in a dictionary is made up of:

  • Key: A unique identifier used to access a value in the dictionary.
  • Value: The data or information associated with the key.

Keys

  • Types of Keys: Keys must be of immutable types. Commonly used types for keys are strings (str), numbers (int, float), and immutable tuples. Lists, sets, and other dictionaries cannot be used as keys because they are mutable.
  • Uniqueness: Keys in a dictionary must be unique. If you add or modify a value using an existing key, the previous value will be overwritten.

Example of Keys: 

d = {
    "name": "Alice",  # key of type string
    42: "The answer",  # key of type integer
    (1, 2): "Tuple key"  # key of type tuple
}
# Example of incorrect key: using a list as a key
# d[[1, 2]] = "List key"  # This will raise a TypeError

Values

  • Types of Values: Values in a dictionary can be of any data type, including strings, numbers, lists, tuples, sets, other dictionaries, and even custom objects.
  • Mutability: Unlike keys, values can be mutable. You can store lists or other dictionaries as values in a dictionary.

Example of Values: 

d = {
    "name": "Alice",  # value of type string
    "age": 30,  # value of type integer
    "hobbies": ["reading", "hiking"],  # value of type list
    "address": {"city": "Paris", "postcode": 75001}  # value of type dictionary
}
print(d["hobbies"])  # Outputs ['reading', 'hiking']
print(d["address"])  # Outputs {'city': 'Paris', 'postcode': 75001}

 Manipulating Keys and Values

You can access, add, modify, and delete keys and values in a dictionary.

Accessing Elements

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

Example: 

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

 Adding or Modifying Elements

  • Adding: Add a new key-value pair by specifying a new key.
  • Modifying: Modify the value associated with an existing key by assigning a new value to 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

  • Using pop(): Removes the key-value pair specified by the key and returns the associated value.
  • Using popitem(): Removes and returns the last key-value pair inserted into the dictionary (available since Python 3.7).
  • Using del: Removes the key-value pair specified by 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 {}

Operations with Keys and Values

Check if a Key Exists

Use the in operator to check if a key is present in the dictionary.

Example: 

d = {
    "name": "Alice",
    "age": 30
}
print("name" in d)  # Outputs True
print("city" in d)  # Outputs False

Retrieve Keys, Values, and Key-Value Pairs

  • .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.

Example: 

d = {
    "name": "Alice",
    "age": 30
}
print(d.keys())   # Outputs dict_keys(['name', 'age'])
print(d.values()) # Outputs dict_values(['Alice', 30])
print(d.items())  # Outputs dict_items([('name', 'Alice'), ('age', 30)])

Using .get()

The .get() method returns the value for a specified key. If the key does not exist, you can provide a default value.

Example: 

d = {
    "name": "Alice",
    "age": 30
}
print(d.get("name"))          # Outputs 'Alice'
print(d.get("city", "Unknown")) # Outputs 'Unknown'

Using .setdefault()

The .setdefault() method returns the value for a specified key. If the key does not exist, it adds the key with a default value and returns that value.

Example: 

d = {
    "name": "Alice",
    "age": 30
}
print(d.setdefault("city", "Paris"))  # Outputs 'Paris'
print(d)  # Outputs {'name': 'Alice', 'age': 30, 'city': 'Paris'}

Summary

  • Keys: Unique identifiers, must be immutable (e.g., strings, numbers, immutable tuples).
  • Values: Can be any data type, including complex data structures.
  • Access: Use brackets to access values via keys.
  • Add/Modify: Add or modify elements by specifying keys.
  • Remove: Use pop(), popitem(), or del to remove elements.
  • Operations: Check key existence, retrieve keys, values, or key-value pairs with appropriate methods.

Laisser un commentaire

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