Python Dictionary Fundamentals and Operations
Dictionary Creation
Python dictionaries can be initialized using curly braces {} or the dict() constructor:
# Creating an empty dictionary
data = {}
# Adding key-value pairs
data["primary"] = "this is the first item"
data["secondary"] = "this is the second item"
data
{'primary': 'this is the first item', 'secondary': 'this is the second item'}
Key Characteristics
Dictionary keys are unordered. When displaying dictionary contents, Python does not guarantee the order matches insertion sequence since keys lack inherent ordering.
Due to this unordered nature, numeric indexing is not supported for dictionary access. Additionally, using numbers as keys can create confusion with sequential access patterns.
Immutable Keys Requirement
For hashing purposes, dictionary keys must be immutable objects, while values can be any Python object:
fruits = {}
fruits['red'] = ['strawberry', 'cherry', 'apple']
fruits['yellow'] = ['banana', 'lemon']
fruits
Output:
{'red': ['strawberry', 'cherry', 'apple'],
'yellow': ['banana', 'lemon']}
Dictionary Initialization with Constructor
inventory = dict([
('laptop', 123),
('mouse', 456),
('keyboard', 789)
])
inventory
{'laptop': 123, 'mouse': 456, 'keyboard': 789}
Suitable Key Types
Among immutable types, integers and string are most commonly used as dictionary keys. Floating-point numbers are generally discouraged due to precision issues that can cause unexpected behavior.
Tuples can also serve as keys since they maintain order. Consequently, ('laptop', 'mouse') and ('mouse', 'laptop') represent distinct keys:
devices = {}
devices[('laptop', 'mouse')] = 100
devices[('mouse', 'laptop')] = 200
print(devices['laptop', 'mouse'])
print(devices['mouse', 'laptop'])
100
200
Dictionary Methods
get Method
Retrieves the value associated with a key, returning a default value (None if unspecified) when the key doesn't exist.
pop Method
devices.pop(('laptop', 'mouse'))
100
update Method
employee = {}
employee['identifier'] = 12
employee['name'] = "Alice"
employee['surname'] = "Smith"
print(employee)
{'identifier': 12, 'name': 'Alice', 'surname': 'Smith'}
Modifying specific fields:
updates = {'identifier': 44, 'name': "Robert"}
employee.update(updates)
print(employee)
{'identifier': 44, 'name': 'Robert', 'surname': 'Smith'}
Membership Testing
'name' in employee
True
keys, values, and items Methods
The keys() method returns a list of all dictionary keys.
The values() method returns all dictionary values.
The items() method returns a list of tuples containing all key-value pairs.