Detailed Explanation of Python Dictionary Methods
Dictionary Object Methods
clear()
- Function: Clears all key-value pairs in the dictionary
- Example:
# Example 1: Clear an existing dictionary
d = {'a':1, 'b':2}
d.clear()
print(d) # {}
# Example 2: Operation on an empty dictionary
d = {}
d.clear()
print(d) # {}
# Example 3: Clear and then add new elements
d = {'x':10}
d.clear()
d['y'] = 20
print(d) # {'y':20}
copy()
- Function: Creates a shallow copy of the dictionary
- Example:
# Example 1: Simple copy
d1 = {'a':1, 'b':[2,3]}
d2 = d1.copy()
d2['a'] = 10
print(d1) # {'a':1, 'b':[2,3]}
# Example 2: Nested object impact
d1['b'].append(4)
print(d2) # {'a':10, 'b':[2,3,4]}
# Example 3: Deep copy
dimport copy
d3 = copy.deepcopy(d1)
d1['b'].append(5)
print(d3) # {'a':1, 'b':[2,3,4]}
fromkeys(iterable[, value])
- Function: Creates a new dictionary from an iterable
- Example:
# Example 1: Default value None
keys = ['a','b','c']
print(dict.fromkeys(keys)) # {'a':None, 'b':None, 'c':None}
# Example 2: Specified default value
print(dict.fromkeys(keys, 0)) # {'a':0, 'b':0, 'c':0}
# Example 3: Mutable object trap
vals = []
d = dict.fromkeys(keys, vals)
d['a'].append(1)
print(d) # {'a':[1], 'b':[1], 'c':[1]}
get(key[, default])
- Function: Safely retrieves the value for a key
- Example:
# Example 1: Key exists
d = {'a':1, 'b':2}
print(d.get('a')) # 1
# Example 2: Key does not exist
print(d.get('c', 'Not Found')) # Not Found
# Example 3: Retrieve from nested dictionary
user = {'profile': {'name':'John'}}
print(user.get('profile', {}).get('name')) # John
items()
- Function: Returns a view of the dictionary’s items
- Example:
# Example 1: Iterate over dictionary items
d = {'a':1, 'b':2}
for k,v in d.items():
print(f'{k}:{v}')
# Example 2: View updates dynamically
d = {'x':10}
view = d.items()
d['y'] = 20
print(list(view)) # dict_items([('x',10), ('y',20)])
# Example 3: Set operations
view1 = {'a':1, 'b':2}.items()
view2 = {'b':2, 'a':1}.items()
print(view1 == view2) # True
keys()
- Function: Returns a view of the dictionary’s keys
- Example:
# Example 1: Get all keys
d = {'a':1, 'b':2}
print(list(d.keys())) # ['a','b']
# Example 2: Check if key exists
print('a' in d.keys()) # True
# Example 3: View updates dynamically
d['c'] = 3
print(list(d.keys())) # ['a','b','c']
pop(key[, default])
- Function: Deletes and returns the value for the specified key
- Example:
# Example 1: Normal deletion
d = {'a':1, 'b':2}
print(d.pop('a')) # 1
print(d) # {'b':2}
# Example 2: Key does not exist with default value
print(d.pop('c', 'Default Value')) # Default Value
# Example 3: Key does not exist without default value
try:
d.pop('c')
except KeyError as e:
print(e) # 'c'
popitem()
- Function: Deletes and returns the last inserted key-value pair
- Example:
# Example 1: Last in, first out
d = {'a':1, 'b':2}
print(d.popitem()) # ('b',2)
print(d.popitem()) # ('a',1)
# Example 2: Operation on an empty dictionary
try:
{}.popitem()
except KeyError:
print('Dictionary is empty')
# Example 3: Insertion order impact
d = {}
d['x'] = 10
d['y'] = 20
print(d.popitem()) # ('y',20)
setdefault(key[, default])
- Function: Safely sets a key-value pair
- Example:
# Example 1: Key does not exist
d = {}
print(d.setdefault('a',1)) # 1
print(d) # {'a':1}
# Example 2: Key exists
d = {'a':10}
print(d.setdefault('a',1)) # 10
# Example 3: Application in nested dictionaries
data = {}
for item in ['apple','banana','apple']:
data.setdefault(item, 0)
data[item] +=1
print(data) # {'apple':2, 'banana':1}
update([other])
- Function: Batch updates the dictionary
- Example:
# Example 1: Merge dictionaries
d = {'a':1}
d.update({'b':2, 'c':3})
print(d) # {'a':1, 'b':2, 'c':3}
# Example 2: List of key-value pairs
d.update([('d',4), ('e',5)])
print(d) # {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
# Example 3: Keyword arguments
d.update(f=6, g=7)
print(d) # {..., 'f':6, 'g':7}
values()
- Function: Returns a view of the dictionary’s values
- Example:
# Example 1: Get all values
d = {'a':1, 'b':2}
print(list(d.values())) # [1,2]
# Example 2: Check if value exists
print(2 in d.values()) # True
# Example 3: View updates dynamically
d['c'] = 3
print(list(d.values())) # [1,2,3]
Adding Elements
- Function: Adds key-value pairs to the dictionary
- Example:
# Example 1: Direct assignment
colors = {}
colors['red'] = '#FF0000'
print(colors) # {'red': '#FF0000'}
# Example 2: Merge using update method
info = {'name': 'Alice'}
info.update({'age': 25, 'city': 'Beijing'})
print(info) # {'name': 'Alice', 'age': 25, 'city': 'Beijing'}
# Example 3: Automatically add using setdefault
data = {}
data.setdefault('counter', 0)
data['counter'] += 1
print(data) # {'counter': 1}
Modifying Elements
- Function: Updates the value of an existing key
- Example:
# Example 1: Direct modification
inventory = {'apples': 10}
inventory['apples'] = 15
print(inventory) # {'apples': 15}
# Example 2: Batch update
config = {'debug': False, 'log_level': 'info'}
config.update({'debug': True, 'timeout': 30})
print(config) # {'debug': True, 'log_level': 'info', 'timeout': 30}
# Example 3: Conditional modification
temperatures = {'room1': 18, 'room2': 22}
for room in temperatures:
if temperatures[room] > 20:
temperatures[room] -= 2
print(temperatures) # {'room1': 18, 'room2': 20}
Iteration Operations
- Function: Access all elements in the dictionary
- Example:
# Example 1: Iterate over keys
student = {'name': 'Bob', 'age': 20, 'major': 'CS'}
for key in student:
print(key)
# Example 2: Iterate over values
for value in student.values():
print(value)
# Example 3: Iterate over key-value pairs
for k, v in student.items():
print(f'{k}: {v}')
Dictionary Comprehensions
- Function: Quickly generate dictionary expressions
- Example:
# Example 1: Simple comprehension
squares = {x: x**2 for x in range(5)}
print(squares) # {0:0, 1:1, 2:4, 3:9, 4:16}
# Example 2: Conditional filtering
even_squares = {k:v for k,v in squares.items() if v%2 ==0}
print(even_squares) # {0:0, 2:4, 4:16}
# Example 3: Key-value transformation
d = {'a':1, 'b':2}
flipped = {v:k for k,v in d.items()}
print(flipped) # {1:'a', 2:'b'}
Ordered Dictionary (OrderedDict)
from collections import OrderedDict
# Example 1: Maintain order
od = OrderedDict()
od['z'] = 3
od['a'] = 1
print(list(od.keys())) # ['z','a']
# Example 2: Order operations
od.move_to_end('z')
print(list(od.keys())) # ['a','z']
# Example 3: Equality check
d1 = {'a':1, 'b':2}
d2 = {'b':2, 'a':1}
print(d1 == d2) # True
print(OrderedDict(d1) == OrderedDict(d2)) # False
Dictionary Merge Operator
# Example 1: Basic merge
d1 = {'a':1, 'b':2}
d2 = {'b':3, 'c':4}
print(d1 | d2) # {'a':1, 'b':3, 'c':4}
# Example 2: Chained merge
d3 = {'d':5}
print(d1 | d2 | d3) # {..., 'd':5}
# Example 3: In-place update
d1 |= d2
print(d1) # {'a':1, 'b':3, 'c':4}
Dictionary View Set Operations
d1 = {'a':1, 'b':2}
d2 = {'b':2, 'c':3}
# Example 1: Key intersection
common_keys = d1.keys() & d2.keys()
print(common_keys) # {'b'}
# Example 2: Item union
all_items = d1.items() | d2.items()
print(all_items) # {('a',1), ('b',2), ('b',2), ('c',3)}
# Example 3: Value difference
unique_values = d1.values() - d2.values()
print(unique_values) # {1}
Dictionary and JSON Conversion
import json
# Example 1: Dictionary to JSON
data = {'name':'Alice', 'age':30, 'skills':['Python','SQL']}
json_str = json.dumps(data, indent=2)
print(json_str)
# Example 2: JSON to dictionary
restored = json.loads(json_str)
print(restored['skills']) # ['Python','SQL']
# Example 3: Special type handling
from datetime import datetime
data = {'time': datetime.now()}
class DateTimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)
print(json.dumps(data, cls=DateTimeEncoder))