Sobes.tech
Junior

What is a mapping in the context of programming and Python?

sobes.tech AI

Answer from AI

Serialization (mapping) is a collection of elements where each element is associated with a unique key. The key is used to access the value. In Python, the main type of mapping is a dictionary (dict).

Key features of mappings:

  • Unique keys: Each key can appear only once.
  • Access by key: Elements are retrieved by their key, not by index (like in lists or tuples).
  • Unordered (in older Python versions): Before Python 3.7, dictionaries were unordered. From Python 3.7 onwards, they preserve insertion order.
  • Mutable: Dictionaries can be changed by adding, removing, or modifying key-value pairs.

In Python, dict implements the mapping protocol, meaning it has certain methods and operations:

  • len(d): Returns the number of key-value pairs.
  • d[key]: Returns the value for the key, or raises KeyError if not found.
  • d[key] = value: Adds or updates the value for the key.
  • del d[key]: Removes the pair by key.
  • key in d: Checks if key exists.
  • d.keys(): Returns a view of keys.
  • d.values(): Returns a view of values.
  • d.items(): Returns a view of key-value pairs.
# Example dictionary
my_dict = {'apple': 1, 'banana': 2, 'orange': 3}

# Access by key
print(my_dict['banana'])

# Modify value
my_dict['apple'] = 5

# Add new element
my_dict['grape'] = 4

# Remove element
del my_dict['orange']

# Check key existence
print('apple' in my_dict)

# Iterate over items
for key, value in my_dict.items():
    print(f"{key}: {value}")