Python3 Func Dict
# Python dict() Function
The `dict()` function is a built-in constructor in Python used to create and initialize dictionaries.
A dictionary is an unordered (or ordered by insertion since Python 3.7), mutable collection of key-value pairs. Each key in a dictionary must be unique and hashable (immutable), while values can be of any data type.
---
## Syntax and Parameters
The `dict()` constructor can be invoked in several ways depending on the input data structure.
### Syntax Formats
```python
dict()
dict(mapping)
dict(iterable, **kwargs)
dict(**kwargs)
```
### Parameter Descriptions
* **`mapping`** *(optional)*:
* **Type**: A mapping object (such as another dictionary).
* **Description**: Creates a new dictionary with the same key-value pairs as the mapping object.
* **`iterable`** *(optional)*:
* **Type**: An iterable object (such as a list or tuple).
* **Description**: Each element in the iterable must itself be an iterable containing exactly two objects (a key and a value), such as `[('key1', 'value1'), ('key2', 'value2')]`.
* **`**kwargs`** *(optional)*:
* **Type**: Keyword arguments.
* **Description**: Passes key-value pairs directly as named arguments (e.g., `name="Tom", age=20`).
### Return Value
* Returns a new **dictionary** (`dict`) object initialized with the given data. If no arguments are provided, it returns an empty dictionary `{}`.
---
## Code Examples
### Example 1: Creating Dictionaries in Different Ways
The following example demonstrates how to initialize dictionaries using empty constructors, keyword arguments, mapping objects, iterables, and the `zip()` function.
```python
# 1. Create an empty dictionary
d = dict()
print(d) # Output: {}
# 2. Create using keyword arguments (highly readable and commonly used)
d = dict(name="Tom", age=20)
print(d) # Output: {'name': 'Tom', 'age': 20}
# 3. Create from an existing mapping object (shallow copy)
d1 = {"name": "Tom"}
d2 = dict(d1)
print(d2) # Output: {'name': 'Tom'}
# 4. Create from an iterable containing key-value pairs (tuples or lists)
pairs = [("name", "Tom"), ("age", 20)]
d = dict(pairs)
print(d) # Output: {'name': 'Tom', 'age': 20}
# 5. Create by pairing keys and values using zip()
keys = ["name", "age", "city"]
values = ["Tom", 20, "Beijing"]
d = dict(zip(keys, values))
print(d) # Output: {'name': 'Tom', 'age': 20, 'city': 'Beijing'}
```
**Expected Output:**
```text
{}
{'name': 'Tom', 'age': 20}
{'name': 'Tom'}
{'name': 'Tom', 'age': 20}
{'name': 'Tom', 'age': 20, 'city': 'Beijing'}
```
**Key Takeaways:**
* Using keyword arguments (`dict(key=value)`) is clean, but keys must be valid Python identifiers (e.g., they cannot start with numbers or contain spaces).
* When using an iterable, each item must contain exactly two elements (a key and a value).
* `dict(zip(keys, values))` is an elegant and efficient way to merge two separate lists into a dictionary.
---
### Example 2: Basic Dictionary Operations
Once a dictionary is created, you can perform standard operations such as accessing, adding, modifying, deleting, and iterating over elements.
```python
# Initialize a dictionary
d = {"name": "Tom", "age": 20}
# 1. Accessing values
print(d) # Output: Tom (Raises KeyError if key does not exist)
print(d.get("age")) # Output: 20 (Returns None if key does not exist)
# 2. Adding and modifying elements
d = "Beijing" # Adds a new key-value pair
d = 21 # Updates the value of an existing key
print(d) # Output: {'name': 'Tom', 'age': 21, 'city': 'Beijing'}
# 3. Deleting elements
del d
print(d) # Output: {'name': 'Tom', 'city': 'Beijing'}
# 4. Iterating through key-value pairs
for key, value in d.items():
print(f"{key}: {value}")
```
**Expected Output:**
```text
Tom
20
{'name': 'Tom', 'age': 21, 'city': 'Beijing'}
{'name': 'Tom', 'city': 'Beijing'}
name: Tom
city: Beijing
```
---
## Important Considerations
1. **Key Constraints**: Dictionary keys must be of an **immutable (hashable)** data type. Strings, numbers, and tuples are valid keys. Lists, sets, and other dictionaries are mutable and cannot be used as keys.
2. **Duplicate Keys**: If duplicate keys are provided during initialization (e.g., in keyword arguments or iterables), the last value specified will overwrite any previous values.
3. **Performance**: Accessing, adding, and deleting items in a dictionary has an average time complexity of **$O(1)$** because dictionaries are implemented using hash tables.
YouTip