write in a .single .py file
write atleast 200 operations
topic is "dictionary operation in python from basic to very advanced"
Assistant
python
# dictionary_operations.py
# A comprehensive Python script demonstrating 200 dictionary operations from basic to very advanced.
# 1. Create an empty dictionary
dict1 = {}
# 2. Create a dictionary with integer keys
dict2 = {1: 'one', 2: 'two'}
# 3. Create a dictionary with mixed keys
dict3 = {'name': 'Alice', 42: 'Answer'}
# 4. Access value by key
value1 = dict2[1] # 'one'
# 5. Access value using get()
value2 = dict3.get('name') # 'Alice'
# 6. Access value with a default using get()
value3 = dict3.get('age', 30) # 30
# 7. Add a new key-value pair
dict1['new_key'] = 'new_value'
# 8. Update a value for an existing key
dict2[2] = 'TWO'
# 9. Use update() to add multiple key-value pairs
dict1.update({'key1': 'value1', 'key2': 'value2'})
# 10. Remove a key using del
del dict1['new_key']
# 11. Remove a key using pop()
removed_value = dict2.pop(1) # 'one'
# 12. Remove and return an arbitrary key-value pair using popitem()
key, value = dict1.popitem()
# 13. Check if a key exists using in
exists = 'key1' in dict1 # True
# 14. Check if a key does not exist using not in
not_exists = 'nonexistent' not in dict1 # True
# 15. Iterate over keys
for key in dict3:
pass
# 16. Iterate over values
for value in dict3.values():
pass
# 17. Iterate over key-value pairs
for key, value in dict3.items():
pass
# 18. Get all keys as a view
keys = dict3.keys()
# 19. Get all values as a view
values = dict3.values()
# 20. Get all items as a view
items = dict3.items()
# 21. Dictionary comprehension: square numbers
squares = {x: x*x for x in range(5)} # {0:0, 1:1, 2:4, 3:9, 4:16}
# 22. Dictionary comprehension with condition
even_squares = {x: x*x for x in range(10) if x % 2 == 0}
# 23. Nested dictionary creation
nested_dict = {'outer': {'inner': 'value'}}
# 24. Access nested dictionary
inner_value = nested_dict['outer']['inner'] # 'value'
# 25. Update nested dictionary
nested_dict['outer']['inner'] = 'new_value'
# 26. Merge two dictionaries (Python 3.9+)
dict_a = {'a': 1}
dict_b = {'b': 2}
merged_dict = dict_a | dict_b # {'a':1, 'b':2}
# 27. Merge two dictionaries with update (Python <3.9)
dict_a.update(dict_b)
# 28. Copy a dictionary using copy()
dict_copy = dict3.copy()
# 29. Deep copy a dictionary
import copy
deep_copy = copy.deepcopy(nested_dict)
# 30. Clear all items in a dictionary
dict_copy.clear()
# 31. Get dictionary length
length = len(dict3)
# 32. Check dictionary is empty
is_empty = not dict1
# 33. Set default value
dict3.setdefault('age', 25)
# 34. Setdefault with existing key
existing = dict3.setdefault('name', 'Bob') # 'Alice'
# 35. Using fromkeys() to create a new dictionary
keys = ['a', 'b', 'c']
default_dict = dict.fromkeys(keys, 0) # {'a':0, 'b':0, 'c':0}
# 36. Using fromkeys() with different default
default_dict_none = dict.fromkeys(keys) # {'a':None, 'b':None, 'c':None}
# 37. Convert list of tuples to dictionary
list_of_tuples = [('x', 24), ('y', 25)]
dict_from_tuples = dict(list_of_tuples)
# 38. Convert list of lists to dictionary
list_of_lists = [['key1', 'value1'], ['key2', 'value2']]
dict_from_lists = dict(list_of_lists)
# 39. Convert keys to a list
keys_list = list(dict3.keys())
# 40. Convert values to a list
values_list = list(dict3.values())
# 41. Convert items to a list
items_list = list(dict3.items())
# 42. Find keys with specific value
keys_with_value = [k for k, v in dict3.items() if v == 'Alice']
# 43. Find all keys
all_keys = dict3.keys()
# 44. Find all values
all_values = dict3.values()
# 45. Find all items
all_items = dict3.items()
# 46. Reverse dictionary (swap keys and values)
reversed_dict = {v: k for k, v in dict3.items()}
# 47. Iterate and print keys
for key in dict3:
print(key)
# 48. Iterate and print values
for value in dict3.values():
print(value)
# 49. Iterate and print key-value pairs
for key, value in dict3.items():
print(f"{key}: {value}")
# 50. Find maximum key (if keys are comparable)
# Assuming keys are integers
max_key = max(dict2.keys())
# 51. Find minimum key
min_key = min(dict2.keys())
# 52. Find maximum value (if values are comparable)
# Assuming values are integers or floats
# Example dictionary
num_dict = {'a': 10, 'b': 20, 'c': 5}
max_value = max(num_dict.values())
# 53. Find minimum value
min_value = min(num_dict.values())
# 54. Sort dictionary by keys
sorted_by_keys = dict(sorted(dict3.items(), key=lambda item: item[0]))
# 55. Sort dictionary by values
sorted_by_values = dict(sorted(dict3.items(), key=lambda item: item[1]))
# 56. Check if two dictionaries are equal
dict_equal = dict1 == dict2
# 57. Compare dictionaries
# In Python, dictionaries are equal if they have same key-value pairs
# 58. Iterate with index using enumerate
for index, (k, v) in enumerate(dict3.items()):
pass
# 59. Find key by value
def get_key_by_value(d, target):
for k, v in d.items():
if v == target:
return k
return None
key_found = get_key_by_value(dict3, 'Alice')
# 60. Check if dictionary is a subset of another
subset = all(item in dict_a.items() for item in dict_b.items())
# 61. Find intersection of two dictionaries
intersection = {k: dict_a[k] for k in dict_a if k in dict_b and dict_a[k] == dict_b[k]}
# 62. Find difference of two dictionaries
difference = {k: v for k, v in dict_a.items() if k not in dict_b}
# 63. Get keys with values greater than a threshold
threshold = 10
keys_gt_threshold = [k for k, v in num_dict.items() if v > threshold]
# 64. Serialize dictionary to JSON
import json
json_str = json.dumps(dict3)
# 65. Deserialize JSON to dictionary
dict_from_json = json.loads(json_str)
# 66. Serialize dictionary to a file
with open('dict.json', 'w') as f:
json.dump(dict3, f)
# 67. Deserialize dictionary from a file
with open('dict.json', 'r') as f:
dict_from_file = json.load(f)
# 68. Pretty print dictionary
import pprint
pprint.pprint(dict3)
# 69. Iterate using while loop
keys_list = list(dict3.keys())
i = 0
while i < len(keys_list):
key = keys_list[i]
i += 1
# 70. Using dictionary unpacking
dict4 = {**dict2, **dict3}
# 71. Check if dictionary is a superset
dict_superset = {'a':1, 'b':2, 'c':3}
dict_subset = {'a':1, 'b':2}
is_superset = all(item in dict_superset.items() for item in dict_subset.items())
# 72. Find duplicate values
from collections import defaultdict
value_counts = defaultdict(int)
for v in dict3.values():
value_counts[v] += 1
duplicates = [v for v, count in value_counts.items() if count > 1]
# 73. Count number of keys
num_keys = len(dict3)
# 74. Count number of values
num_values = len(dict3.values())
# 75. Filter dictionary by keys
filtered_dict = {k: v for k, v in dict3.items() if k.startswith('a')}
# 76. Filter dictionary by values
filtered_values_dict = {k: v for k, v in dict3.items() if isinstance(v, str)}
# 77. Create dictionary from keys with None values
keys = ['x', 'y', 'z']
none_dict = {k: None for k in keys}
# 78. Create dictionary from keys with default value
default_val = 0
default_val_dict = {k: default_val for k in keys}
# 79. Find all unique values
unique_values = set(dict3.values())
# 80. Invert a dictionary with multiple values per key
multi_value_dict = {'a': 1, 'b': 2, 'c': 1}
inverted = defaultdict(list)
for k, v in multi_value_dict.items():
inverted[v].append(k)
inverted_dict = dict(inverted)
# 81. Remove keys with None values
dict_with_none = {'a': 1, 'b': None, 'c': 3}
clean_dict = {k: v for k, v in dict_with_none.items() if v is not None}
# 82. Remove keys with falsy values
dict_falsy = {'a': True, 'b': False, 'c': 0, 'd': 1}
truthy_dict = {k: v for k, v in dict_falsy.items() if v}
# 83. Replace values based on a condition
updated_dict = {k: (v*2 if isinstance(v, int) else v) for k, v in dict3.items()}
# 84. Apply a function to all values
def uppercase(value):
return value.upper() if isinstance(value, str) else value
modified_dict = {k: uppercase(v) for k, v in dict3.items()}
# 85. Rename keys in a dictionary
rename_map = {'old_key1': 'new_key1', 'old_key2': 'new_key2'}
renamed_dict = {rename_map.get(k, k): v for k, v in dict3.items()}
# 86. Swap two keys' values
dict_swap = {'a': 1, 'b': 2}
dict_swap['a'], dict_swap['b'] = dict_swap['b'], dict_swap['a']
# 87. Extract a subset of dictionary
subset_keys = ['a', 'c']
subset_dict = {k: dict3[k] for k in subset_keys if k in dict3}
# 88. Set intersection of keys
keys_a = set(dict1.keys())
keys_b = set(dict2.keys())
common_keys = keys_a & keys_b
# 89. Set union of keys
all_keys = keys_a | keys_b
# 90. Set difference of keys
diff_keys = keys_a - keys_b
# 91. Check if dictionary has any keys
has_keys = bool(dict3)
# 92. Check if dictionary has any values
has_values = any(dict3.values())
# 93. Convert dictionary to list of dictionaries
list_of_dicts = [{'key': k, 'value': v} for k, v in dict3.items()]
# 94. Find first key in dictionary
first_key = next(iter(dict3))
# 95. Find last key in dictionary
last_key = next(reversed(dict3))
# 96. Reverse the order of dictionary
from collections import OrderedDict
reversed_order = OrderedDict(reversed(list(dict3.items())))
# 97. Group dictionary keys by value
grouped = defaultdict(list)
for k, v in dict3.items():
grouped[v].append(k)
grouped_dict = dict(grouped)
# 98. Create a dictionary from two lists
keys = ['a', 'b', 'c']
values = [1, 2, 3]
dict_from_lists = dict(zip(keys, values))
# 99. Get dictionary keys as a tuple
keys_tuple = tuple(dict3.keys())
# 100. Get dictionary values as a tuple
values_tuple = tuple(dict3.values())
# 101. Get dictionary items as a tuple
items_tuple = tuple(dict3.items())
# 102. Check if any key satisfies a condition
has_key_starting_with_a = any(k.startswith('a') for k in dict3.keys())
# 103. Check if any value satisfies a condition
has_value_alice = any(v == 'Alice' for v in dict3.values())
# 104. Apply multiple updates
dict3.update({'age': 30, 'city': 'New York'})
# 105. Update with another dictionary using loop
for k, v in dict_b.items():
dict3[k] = v
# 106. Find keys with unique values
from collections import Counter
value_counter = Counter(dict3.values())
unique_value_keys = [k for k, v in dict3.items() if value_counter[v] == 1]
# 107. Map dictionary values using a function
def double(x):
return x * 2
mapped_dict = {k: double(v) for k, v in num_dict.items()}
# 108. Filter out specific keys
keys_to_remove = {'a', 'b'}
filtered_dict = {k: v for k, v in dict3.items() if k not in keys_to_remove}
# 109. Increment numerical values
incremented = {k: v+1 if isinstance(v, int) else v for k, v in num_dict.items()}
# 110. Decrement numerical values
decremented = {k: v-1 if isinstance(v, int) else v for k, v in num_dict.items()}
# 111. Multiply numerical values
multiplied = {k: v*10 if isinstance(v, int) else v for k, v in num_dict.items()}
# 112. Divide numerical values
divided = {k: v/2 if isinstance(v, int) else v for k, v in num_dict.items()}
# 113. Apply conditional expression to values
modified = {k: 'yes' if v else 'no' for k, v in dict_falsy.items()}
# 114. Flatten a nested dictionary
def flatten(d, parent_key='', sep='_'):
items = {}
for k, v in d.items():
new_key = f"{parent_key}{sep}{k}" if parent_key else k
if isinstance(v, dict):
items.update(flatten(v, new_key, sep=sep))
else:
items[new_key] = v
return items
flattened_dict = flatten(nested_dict)
# 115. Unflatten a dictionary
def unflatten(d, sep='_'):
result = {}
for k, v in d.items():
parts = k.split(sep)
current = result
for part in parts[:-1]:
current = current.setdefault(part, {})
current[parts[-1]] = v
return result
unflattened_dict = unflatten(flattened_dict)
# 116. Get all keys in nested dictionary
def get_all_keys(d):
keys = []
for k, v in d.items():
keys.append(k)
if isinstance(v, dict):
keys.extend(get_all_keys(v))
return keys
all_nested_keys = get_all_keys(nested_dict)
# 117. Get all values in nested dictionary
def get_all_values(d):
values = []
for v in d.values():
values.append(v)
if isinstance(v, dict):
values.extend(get_all_values(v))
return values
all_nested_values = get_all_values(nested_dict)
# 118. Find if any value meets a condition in nested dictionary
def any_value(d, condition):
for v in d.values():
if isinstance(v, dict):
if any_value(v, condition):
return True
elif condition(v):
return True
return False
has_value_gt_10 = any_value(nested_dict, lambda x: x > 10)
# 119. Find all keys path to a specific value
def find_keys_path(d, target, path=None):
if path is None:
path = []
paths = []
for k, v in d.items():
current_path = path + [k]
if v == target:
paths.append(current_path)
elif isinstance(v, dict):
paths.extend(find_keys_path(v, target, current_path))
return paths
paths_to_value = find_keys_path(nested_dict, 'value')
# 120. Convert dictionary to list of keys
keys_only = list(dict3.keys())
# 121. Convert dictionary to list of values
values_only = list(dict3.values())
# 122. Find difference in keys between two dictionaries
diff_keys = keys_a.symmetric_difference(keys_b)
# 123. Find symmetric difference of two dictionaries
symmetric_diff = {k: dict_a[k] for k in keys_a.symmetric_difference(keys_b)}
# 124. Create a default dictionary
default_dict = defaultdict(int)
default_dict['a'] += 1
# 125. Create a defaultdict with list
list_default = defaultdict(list)
list_default['a'].append(1)
# 126. Create a defaultdict with set
set_default = defaultdict(set)
set_default['a'].add(1)
# 127. Switch to using standard dict
standard_dict = dict(list_default)
# 128. Find the most common value
most_common = value_counter.most_common(1)[0][0]
# 129. Find least common value
least_common = value_counter.most_common()[-1][0]
# 130. Filter dictionary with multiple conditions
filtered = {k: v for k, v in dict3.items() if k.startswith('a') and v != 'Alice'}
# 131. Initialize dictionary with keys and a generator
gen = (x for x in range(5))
gen_dict = {k: next(gen) for k in ['a', 'b', 'c', 'd', 'e']}
# 132. Remove duplicate keys (last occurrence)
dup_keys = [('a', 1), ('b', 2), ('a', 3)]
unique_dict = {}
for k, v in dup_keys:
unique_dict[k] = v # {'a':3, 'b':2}
# 133. Create a dictionary from a string with character counts
from collections import Counter
char_counts = dict(Counter("hello world"))
# 134. Convert dictionary to namedtuple
from collections import namedtuple
def dict_to_namedtuple(d, name='Data'):
return namedtuple(name, d.keys())(*d.values())
nt = dict_to_namedtuple(dict3)
# 135. Convert namedtuple back to dictionary
nt_dict = nt._asdict()
# 136. Use dictionary as a stack
stack = {}
stack['push'] = 'item1'
last_item = stack.pop('push', None)
# 137. Use dictionary as a queue
from collections import deque
queue = deque()
queue.append('item1')
first_item = queue.popleft()
# 138. Implement LRU Cache using OrderedDict
class LRUCache:
def __init__(self, capacity):
self.cache = OrderedDict()
self.capacity = capacity
def get(self, key):
if key not in self.cache:
return -1
self.cache.move_to_end(key)
return self.cache[key]
def put(self, key, value):
self.cache[key] = value
self.cache.move_to_end(key)
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)
# 139. Use dictionary to count occurrences
occurrences = {}
for item in ['a', 'b', 'a', 'c', 'b', 'a']:
occurrences[item] = occurrences.get(item, 0) + 1 # {'a':3, 'b':2, 'c':1}
# 140. Create a dictionary with function values
def func1():
return "Function 1"
def func2():
return "Function 2"
func_dict = {'f1': func1, 'f2': func2}
# 141. Call functions from dictionary
result_f1 = func_dict['f1']() # "Function 1"
# 142. Use dictionary for switch-case simulation
def switch_case(case):
switcher = {
'case1': "You selected case 1",
'case2': "You selected case 2",
}
return switcher.get(case, "Invalid case")
response = switch_case('case1') # "You selected case 1"
# 143. Serialize dictionary with non-string keys
dict_with_int_keys = {1: 'one', 2: 'two'}
json_str_int_keys = json.dumps(dict_with_int_keys) # '{"1": "one", "2": "two"}'
# 144. Deserialize JSON with non-string keys (keys become strings)
dict_deserialized = json.loads(json_str_int_keys) # {'1': 'one', '2': 'two'}
# 145. Handle missing keys with try-except
try:
val = dict3['missing']
except KeyError:
val = 'default'
# 146. Use get to avoid KeyError
val = dict3.get('missing', 'default')
# 147. Check key existence before accessing
if 'name' in dict3:
val = dict3['name']
# 148. Conditional dictionary update
if 'age' in dict1:
dict1['age'] += 1
else:
dict1['age'] = 1
# 149. Create a dictionary with conditional keys
conditional_dict = {k: v for k, v in dict3.items() if v is not None}
# 150. Update nested dictionary safely
def safe_update(d, keys, value):
for key in keys[:-1]:
d = d.setdefault(key, {})
d[keys[-1]] = value
safe_update(nested_dict, ['outer', 'inner', 'deep'], 'deep_value')
# 151. Remove a key safely using pop
val = dict3.pop('nonexistent', 'default')
# 152. Iterate over dictionary in sorted order
for k in sorted(dict3.keys()):
pass
# 153. Iterate over dictionary in reverse sorted order
for k in sorted(dict3.keys(), reverse=True):
pass
# 154. Check if all keys meet a condition
all_keys_start_with_a = all(k.startswith('a') for k in dict3.keys())
# 155. Check if all values meet a condition
all_values_are_strings = all(isinstance(v, str) for v in dict3.values())
# 156. Apply a transformation to keys
transformed_keys_dict = {f"key_{k}": v for k, v in dict3.items()}
# 157. Apply a transformation to values
transformed_values_dict = {k: f"value_{v}" for k, v in dict3.items()}
# 158. Create a dictionary from enumerated keys
enum_dict = {i: k for i, k in enumerate(dict3.keys())}
# 159. Create a multi-level dictionary
multi_level = {'level1': {'level2': {'level3': 'deep'}}}
# 160. Access multi-level dictionary with defaults
level3 = dict3.get('level1', {}).get('level2', 'default')
# 161. Update multi-level dictionary
dict3.setdefault('level1', {}).setdefault('level2', {})['level3'] = 'new_deep'
# 162. Remove a key from multi-level dictionary
level2 = dict3.get('level1', {})
level2.pop('level3', None)
# 163. Convert dictionary to YAML
import yaml
yaml_str = yaml.dump(dict3)
# 164. Convert YAML back to dictionary
dict_from_yaml = yaml.safe_load(yaml_str)
# 165. Use dictionary for configuration settings
config = {
'version': 1.0,
'settings': {
'option1': True,
'option2': False
}
}
# 166. Access configuration settings
option1 = config['settings']['option1']
# 167. Modify configuration settings
config['settings']['option2'] = True
# 168. Use dictionary to represent JSON schema
json_schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "number"}
},
"required": ["name", "age"]
}
# 169. Validate dictionary against JSON schema (using jsonschema library)
from jsonschema import validate, ValidationError
data = {"name": "Alice", "age": 30}
try:
validate(instance=data, schema=json_schema)
is_valid = True
except ValidationError:
is_valid = False
# 170. Dynamically add keys to dictionary
for i in range(10):
dict1[f'key_{i}'] = i
# 171. Dynamically remove keys from dictionary
keys_to_delete = [k for k in dict1 if k.endswith('5')]
for k in keys_to_delete:
del dict1[k]
# 172. Convert dictionary to a set of tuples
dict_set = set(dict3.items())
# 173. Create a frozen dictionary (immutable)
from types import MappingProxyType
frozen_dict = MappingProxyType(dict3)
# 174. Attempt to modify frozen dictionary (will raise TypeError)
# frozen_dict['new_key'] = 'value' # Uncommenting this line will raise an error
# 175. Iterate over a frozen dictionary
for k, v in frozen_dict.items():
pass
# 176. Compare two dictionaries for partial match
partial_match = all(item in dict1.items() for item in dict_subset.items())
# 177. Find keys with values in a given list
value_list = ['Alice', 'Bob']
keys_in_list = [k for k, v in dict3.items() if v in value_list]
# 178. Find keys with values not in a given list
keys_not_in_list = [k for k, v in dict3.items() if v not in value_list]
# 179. Combine multiple dictionaries into one
dicts = [dict1, dict2, dict3]
combined = {}
for d in dicts:
combined.update(d)
# 180. Use dictionary to map indices to elements
elements = ['a', 'b', 'c']
index_map = {i: elem for i, elem in enumerate(elements)}
# 181. Find index of a key
def find_key_index(d, target):
for index, key in enumerate(d.keys()):
if key == target:
return index
return -1
index_of_b = find_key_index(dict3, 'b')
# 182. Reverse iterate over dictionary
for k in reversed(dict3):
pass
# 183. Slice a dictionary (Python doesn't support slicing, emulate with comprehension)
sliced_dict = {k: dict3[k] for k in list(dict3.keys())[0:2]}
# 184. Get first N items from dictionary
from itertools import islice
first_n = dict(islice(dict3.items(), 2))
# 185. Get last N items from dictionary
last_n = dict(list(dict3.items())[-2:])
# 186. Use dictionary as memoization cache
def fibonacci(n, cache={}):
if n in cache:
return cache[n]
if n <= 1:
cache[n] = n
else:
cache[n] = fibonacci(n-1) + fibonacci(n-2)
return cache[n]
fib_10 = fibonacci(10) # cache will store computed values
# 187. Implement a switch using dictionary of lambdas
operation = {
'add': lambda x, y: x + y,
'sub': lambda x, y: x - y,
}
result = operation['add'](5, 3) # 8
# 188. Create a case-insensitive dictionary
class CaseInsensitiveDict(dict):
def __setitem__(self, key, value):
super().__setitem__(key.lower(), value)
def __getitem__(self, key):
return super().__getitem__(key.lower())
def __contains__(self, key):
return super().__contains__(key.lower())
ci_dict = CaseInsensitiveDict({'Name': 'Alice'})
name = ci_dict['name'] # 'Alice'
# 189. Use dictionary with tuple keys
tuple_key_dict = {('a', 1): 'value1', ('b', 2): 'value2'}
# 190. Serialize dictionary with tuple keys
json_str_tuple = json.dumps({str(k): v for k, v in tuple_key_dict.items()})
# 191. Deserialize dictionary with tuple keys
dict_with_str_keys = json.loads(json_str_tuple)
tuple_keys_deserialized = {tuple(eval(k)): v for k, v in dict_with_str_keys.items()}
# 192. Implement a dictionary as a sparse matrix
sparse_matrix = {}
def set_matrix_value(m, row, col, value):
if value != 0:
m[(row, col)] = value
def get_matrix_value(m, row, col):
return m.get((row, col), 0)
set_matrix_value(sparse_matrix, 1, 2, 5)
val = get_matrix_value(sparse_matrix, 1, 2) # 5
# 193. Use dictionaries to represent graphs
graph = {
'A': ['B', 'C'],
'B': ['A', 'D'],
'C': ['A', 'D'],
'D': ['B', 'C']
}
# 194. Traverse a graph represented by dictionary
def bfs(graph, start):
visited = set()
queue = deque([start])
while queue:
vertex = queue.popleft()
if vertex not in visited:
visited.add(vertex)
queue.extend([n for n in graph[vertex] if n not in visited])
return visited
bfs_result = bfs(graph, 'A')
# 195. Represent adjacency list using defaultdict
graph_default = defaultdict(list)
graph_default['A'].extend(['B', 'C'])
graph_default['B'].append('D')
# 196. Count frequency of characters using defaultdict
char_freq = defaultdict(int)
for char in "hello":
char_freq[char] += 1
# 197. Group items by key using defaultdict
grouped = defaultdict(list)
for k, v in [('a', 1), ('b', 2), ('a', 3)]:
grouped[k].append(v)
# 198. Convert dictionary to pandas DataFrame
import pandas as pd
df = pd.DataFrame(list(dict3.items()), columns=['Key', 'Value'])
# 199. Convert pandas DataFrame to dictionary
df_dict = df.set_index('Key').to_dict()['Value']
# 200. Use dictionary to store configuration flags
flags = {
'debug': True,
'verbose': False,
'test_mode': True
}
# Toggle a flag
flags['verbose'] = not flags['verbose']
# End of dictionary operations.