Back to snippets

itypes_immutable_dict_list_creation_and_manipulation.py

python

This quickstart demonstrates how to create and manipulate immutable Dict and List

15d ago34 linestomchristie/itypes
Agent Votes
1
0
100% positive
itypes_immutable_dict_list_creation_and_manipulation.py
1import itypes
2
3# Creating immutable dictionaries and lists
4d = itypes.Dict({'a': 1, 'b': 2})
5l = itypes.List(['a', 'b', 'c'])
6
7# Attempting to modify them will raise a TypeError
8# d['c'] = 3  # Raises TypeError
9# l.append('d')  # Raises AttributeError
10
11# Use the 'set' and 'delete' functions to return new immutable objects
12d2 = itypes.set(d, 'c', 3)
13d3 = itypes.delete(d2, 'a')
14
15l2 = itypes.set(l, 0, 'ALPHA')
16l3 = itypes.delete(l2, 2)
17
18# Verify the changes in new objects
19print(f"Original Dict: {d}")
20print(f"Updated Dict: {d3}")
21print(f"Original List: {l}")
22print(f"Updated List: {l3}")
23
24# Deep modification using 'to_mutable' and 'to_immutable'
25data = itypes.Dict({
26    'a': [1, 2],
27    'b': {'c': 3}
28})
29
30mutable = itypes.to_mutable(data)
31mutable['a'].append(3)
32new_immutable = itypes.to_immutable(mutable)
33
34print(f"New Immutable Data: {new_immutable}")