<jupyter_start><jupyter_text>Mapping Keys to Multiple Values in a Dictionary  Problem- You want to make a dictionary that maps keys to more than one value (a so-called “multidict”).  Solution- If you want to map keys to multiple values, you need to store the multiple values in another container such as a list or set.- To easily construct such dictionaries, you can use __`defaultdict`__ in the __`collections`__ module. A feature of __`defaultdict`__ is that it automatically initializes the first value so you can simply focus on adding items.<jupyter_code>from collections import defaultdict
d = defaultdict(list)
d['a'].append(1)
d['a'].append(2)
d['b'].append(4)

print(d)
d = defaultdict(set)
d['a'].add(1)
d['a'].add(2)
d['a'].add(2)
d['b'].add(4)

print(d)<jupyter_output>defaultdict(<class 'set'>, {'a': {1, 2}, 'b': {4}})<jupyter_text>Discussion- We compare 2 ways of constructing a multivalued dictionary.<jupyter_code>d = {}
for key, value in pairs:
    if key not in d: 
        d[key] = []
    d[key].append(value)<jupyter_output><empty_output><jupyter_text>- The `defauldict` is much simpler<jupyter_code>d = defaultdict(list) 
for key, value in pairs: 
    d[key].append(value)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12663398692810457, 'fraction_numerical': 0.008986928104575163, 'mean_word_length': 5.314432989690721, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '81735', 'license': 'MIT', 'n_tokens_mistral': 420, 'n_tokens_neox': 403, 'n_words': 140, 'path': 'notebooks/ch01/06_mapping_keys_to_multiple_values_in_a_dictionary.ipynb', 'repo_name': 'tuanavu/python-gitbook', 'size': '1224'}