Att Dictionary Fromkeys
## Python Dictionary fromkeys() Method
The `fromkeys()` method is a built-in Python dictionary method used to create a new dictionary from a given sequence of keys. Each key in the new dictionary is initialized to a specified value (which defaults to `None`).
---
## Syntax
The syntax for the `fromkeys()` method is as follows:
```python
dict.fromkeys(iterable[, value])
```
### Parameters
* **`iterable`**: Any iterable object (such as a list, tuple, set, or string) containing the elements that will become the keys of the new dictionary.
* **`value`** *(Optional)*: The initial value assigned to each key in the dictionary. If omitted, it defaults to `None`.
### Return Value
* Returns a **new dictionary** populated with the keys from the iterable, with each key mapped to the specified value.
---
## Code Examples
### Example 1: Basic Usage (With and Without a Default Value)
The following example demonstrates how to create a dictionary using a tuple of keys, both with and without specifying a default value.
```python
# Define a sequence of keys
seq = ('Google', 'YouTip', 'Taobao')
# 1. Without specifying a default value (defaults to None)
new_dict_none = dict.fromkeys(seq)
print("Dictionary with default None:")
print(new_dict_none)
# 2. Specifying a default value of 10
new_dict_val = dict.fromkeys(seq, 10)
print("\nDictionary with default value 10:")
print(new_dict_val)
```
**Output:**
```text
Dictionary with default None:
{'Google': None, 'YouTip': None, 'Taobao': None}
Dictionary with default value 10:
{'Google': 10, 'YouTip': 10, 'Taobao': 10}
```
---
## Important Considerations
### 1. The Mutable Value Pitfall (Shallow Copying)
When using `fromkeys()` with a **mutable object** (such as a list or a dictionary) as the default `value`, Python assigns the **same reference** to every key. Modifying the value of one key will unexpectedly modify the values of all other keys.
#### Problematic Example:
```python
# Using a mutable list as the default value
keys = ('a', 'b', 'c')
my_dict = dict.fromkeys(keys, [])
print("Initial dictionary:")
print(my_dict)
# Append an item to the list of key 'a'
my_dict['a'].append(100)
print("\nAfter appending 100 to key 'a':")
print(my_dict)
```
**Output:**
```text
Initial dictionary:
{'a': [], 'b': [], 'c': []}
After appending 100 to key 'a':
{'a': , 'b': , 'c': }
```
* **Why this happens:** All keys (`'a'`, `'b'`, and `'c'`) point to the exact same list object in memory.
* **The Solution:** If you need independent mutable objects (like empty lists) for each key, use a **dictionary comprehension** instead:
```python
# Safe alternative using dictionary comprehension
keys = ('a', 'b', 'c')
my_dict = {key: [] for key in keys}
my_dict['a'].append(100)
print(my_dict)
# Output: {'a': , 'b': [], 'c': []}
```
YouTip