Detailed Notes on Python Dictionaries
Detailed Notes on Python Dictionaries with Clarifications on Confusing Points
Introduction to Dictionaries
Definition: A dictionary in Python is a collection of key-value pairs, where each key is unique and associated with a specific value. Dictionaries are mutable, meaning the values they contain can be updated.
Characteristics:
- Unordered: The order of entries in a dictionary is not maintained, making it different from other data structures like lists or tuples.
- Mutable: Values in a dictionary can be altered, added, or removed.
- Indexed by Keys: Instead of numerical indexes, dictionaries use the unique keys to store and retrieve data.
Example of a Dictionary:
emp = {"empno": 1, "name": "Shahrukh", "fee": 1500000}
Creating a Dictionary
Syntax:
dictionary_name = {key1: value1, key2: value2, ...}
Examples:
- Empty dictionary:
Dict1 = {}
- Dictionary with initial values:
DaysInMonth = {"Jan": 31, "Feb": 28, ...}
Note: Keys must be of an immutable type like strings, numbers, or tuples.
Accessing Elements
Creating dictionaries in Python can be done in several ways, each useful depending on the context and what data you have available. Here’s an overview of multiple methods to create dictionaries:
1. Using Curly Braces
The most straightforward method involves using curly braces with key-value pairs separated by commas. Here, both keys and values can be directly listed.
Example:
employee = {"name": "Alice", "role": "Engineer", "id": 123}
2. Using the dict()
Constructor
This method involves the dict()
constructor, which is versatile and can be used in several different ways:
- Direct key-value pairs:
employee = dict(name="Alice", role="Engineer", id=123)
- List of tuples:
Each tuple corresponds to a key-value pair.
employee = dict([("name", "Alice"), ("role", "Engineer"), ("id", 123)])
- From two lists using
zip()
:zip()
combines two lists into a single iterable of tuples, whichdict()
can convert into a dictionary.
keys = ["name", "role", "id"]
values = ["Alice", "Engineer", 123]
employee = dict(zip(keys, values))
3. Using Dictionary Comprehensions
This method is similar to list comprehensions but for dictionaries. It’s powerful for transforming one dictionary or any iterable into a dictionary based on some condition or operation.
Example:
squares = {x: x*x for x in range(6)} # Creates a dictionary of numbers and their squares
4. From Keys
This initializes a dictionary from keys, setting all of them to the same initial value (default is None
).
- Using
fromkeys()
:
This is useful when you need to initialize a dictionary with keys and a uniform value.
keys = ["name", "role", "id"]
employee = dict.fromkeys(keys)
5. Using collections.defaultdict
While not a way to create a dictionary directly, defaultdict
in the collections
module can be very handy when you want a dictionary to automatically assign a default value to non-existent keys.
Example:
from collections import defaultdict
employee = defaultdict(lambda: "unknown")
employee["name"] = "Alice" # Sets "Alice" to "name"
print(employee["role"]) # Prints "unknown" since "role" was not set
Each of these methods has its use cases depending on what data you start with and what your particular needs are for the dictionary creation.
You access elements in a dictionary by referencing the key:
mydict = {'empno': 1, 'name': 'Shivam', 'salary': 25000}
print(mydict['salary']) # Outputs: 25000
If you access a key that does not exist, it will raise a KeyError
.
Traversing a Dictionary
You can traverse a dictionary using a for loop by iterating over the keys:
for key in mydict:
print(key, '=', mydict[key])
Common Methods
keys()
: Returns the keys of the dictionary.values()
: Returns the values of the dictionary.items()
: Returns key-value pairs as a tuple.
Example:
print(list(mydict.keys())) # ['empno', 'name', 'dept', 'salary']
Confusing Points Clarified
- Mutable vs Immutable: Unlike lists (mutable), strings and tuples (both immutable) cannot be changed once created. Dictionaries are mutable like lists.
append()
vsextend()
in Lists: In dictionaries, similar confusion might arise withupdate()
which adds key-value pairs from another dictionary, potentially replacing existing keys.- Access by Key, not Index: Unlike lists where you access elements by a range of numbers, dictionaries use unique keys.
Updating and Deleting
You can update or add new key-value pairs simply by assigning a value to a key:
data = {1: 100, 2: 200}
data[3] = 300 # Adding a new key-value pair
data[1] = 101 # Updating existing key
To delete items, use the del
statement or pop()
:
del data[2] # Removes key 2
print(data.pop(3)) # Removes key 3 and returns its value
Use of pop()
The pop()
method is particularly useful because it allows you to remove an item and return the value. This differs from del
, which only removes the item.
Example:
value = data.pop(1, 'Not found') # Removes key 1 and returns its value, or 'Not found' if key does not exist