
PYTHON — Built-In Dictionary in Python
In technology, whatever can be done will be done. — Andrew S. Grove

PYTHON — Modifying Values Accessor Methods in Python
## Understanding Built-In Dictionaries in Python
In Python, dictionaries are a built-in data type that allows you to store data by mapping a key to a value. This can be used for various purposes such as mapping a name to a phone number or an IP address to a domain name. Dictionaries are known by different names in computer science, such as maps, hashmaps, lookup tables, and associative arrays.
Python uses the native term ‘dict’ for this kind of data structure. The dict type is a fundamental aspect of the language, and many concepts inside Python are built on top of it. It uses curly braces to indicate a dictionary. Here's an example of a dictionary mapping people’s names to their phone extensions:
phonebook = {
"bob": 1234,
"alice": 3719,
"janet": 5678
}To access a value in the dictionary, you can use square brackets and the key:
print(phonebook["alice"]) # Output: 3719If you try to access a key that doesn’t exist, you’ll get a KeyError:
print(phonebook["fred"]) # KeyError: 'fred'To handle this, you can use the .get() method which allows you to specify a default value to return if the key doesn't exist:
print(phonebook.get("fred", "Not found")) # Output: Not foundYou can also get all the keys, values, or key-value pairs from the dictionary using the .keys(), .values(), and .items() methods respectively.
print(phonebook.keys()) # Output: dict_keys(['bob', 'alice', 'janet'])
print(phonebook.values()) # Output: dict_values([1234, 3719, 5678])
print(phonebook.items()) # Output: dict_items([('bob', 1234), ('alice', 3719), ('janet', 5678)])Python also supports dictionary comprehensions, which are a way of creating dictionaries from an iterable. Here’s an example of a dictionary comprehension to create a dictionary of names and their corresponding ranks:
ranks = ["Captain", "Commander", "Lieutenant", "Lieutenant Commander"]
rank_dict = {name: rank for name, rank in zip(["Kirk", "Spock", "Uhura", "McCoy"], ranks)}
print(rank_dict) # Output: {'Kirk': 'Captain', 'Spock': 'Commander', 'Uhura': 'Lieutenant', 'McCoy': 'Lieutenant Commander'}Python dictionaries are highly performant with an order 1 complexity for lookup, insert, update, and delete operations. In addition to the built-in dict type, Python also has other kinds of dictionaries such as OrderedDict and defaultdict.
In the next lesson, we’ll delve into OrderedDict and defaultdict to further enhance your understanding of dictionaries in Python.






