Python Dictionaries
Python Dictionaries
What is a Dictionary?
A dictionary in Python is an unordered collection of key-value pairs. It's like a real-world dictionary where you look up a word (key) to find its definition (value).
What are the features of the dictionary in Python?
In Python, a dictionary is an unordered collection of items that stores data in key-value pairs. Here are the key features of dictionaries:
- Key-Value Pairs: Each item in a dictionary consists of a key and a corresponding value. Keys must be unique and immutable (e.g., strings, numbers, tuples), while values can be of any data type.
- Unordered: Dictionaries do not maintain the order of items. However, as of Python 3.7, dictionaries preserve the insertion order of keys.
- Mutable: Dictionaries can be modified after creation. You can add, remove, or change items.
- Dynamic Size: The size of a dictionary can grow or shrink as items are added or removed.
- Fast Lookups: Dictionaries provide average-case time complexity of O(1) for lookups, insertions, and deletions due to their underlying hash table implementation.
- Nested Dictionaries: Dictionaries can contain other dictionaries as values, allowing for more complex data structures.
- Comprehensions: Python supports dictionary comprehensions, allowing for concise creation of dictionaries using a single line of code.
- Methods: Dictionaries come with various built-in methods, such as:
-dict.keys()
: Returns a view object displaying a list of all the keys.
-dict.values()
: Returns a view object displaying a list of all the values.
-dict.items()
: Returns a view object displaying a list of key-value pairs.
-dict.get(key)
: Retrieves the value for the specified key, returningNone
if the key does not exist.
-dict.pop(key)
: Removes the specified key and returns its value.
Example of a Dictionary
Features:
- Keys are unique: Dictionary keys must be unique. Having duplicate keys defeats the purpose of using a dictionary to store information.
- Keys Must be immutable: Dictionary keys must be of an immutable type. Strings and numbers are the two most commonly used data types as dictionary keys.
- Dictionaries are unordered: A dictionary contains key-value pairs but does not possess an order for the pairs. Thus, a more precise definition is that a dictionary is an unordered collection of key-value pairs. NOTE: In python 3.6x dictionaries have become an ordered collection.
Creating a Dictionary:
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
Accessing Values:
You can access values using their corresponding keys:
print(my_dict['name']) # Output: Alice
Adding or Modifying Values:
my_dict['country'] = 'USA' # Add a new key-value pair
my_dict['age'] = 31 # Modify an existing value
Common Dictionary Methods:
- keys(): Returns a list of all keys.
- values(): Returns a list of all values.
- items(): Returns a list of key-value
1 pairs as tuples.
Comments
Post a Comment