Skip to main content

Modify deep dictionary properties without modifying the original dictionary (immutability)

Project description

Dict_Path_Immutable

Tiny Python library to modify deep dictionary properties without modifying the original dictionary (immutability).

Install

pip install Dict_Path_Immutable

Quick usage

The following, sets a property without modifying the original dictionary. It will minimize the number of clones down the line. The resulting dictionary is just a plain Python dictionary, so be warned that it will not be protected against property mutations

my_dict = {
  a: {
    b: 'c',
    c: ['d', 'f']
  }
}

new_dict = Dict_Path_Immutable.set(my_dict, 'a.b', 'f')
# {
#   a: {
#     b: 'f',
#     c: ['d', 'f']
#   }
# }

API

# Premises

my_dict = {
  a: {
    b: 'c',
    c: ['d', 'f']
  }
}

from Dict_Path_Immutable import Dict_Path_Immutable

set (initialDict, path, value)

Changes a dictionary property.

  • Path can be either a string or an array.
new_dict1 = Dict_Path_Immutable.set(my_dict, 'a.b', 'f')
new_dict2 = Dict_Path_Immutable.set(my_dict, ['a', 'b'], 'f')

# {
#   a: {
#     b: 'f',
#     c: ['d', 'f']
#   }
# }

# Note that if the path is specified as a string, numbers are automatically interpreted as array indexes.

new_dict = Dict_Path_Immutable.set(my_dict, 'a.c.1', 'fooo')
# {
#   a: {
#     b: 'f',
#     c: ['d', 'fooo']
#   }
# }

delete (initialDict, path)

Deletes a property.

new_dict = Dict_Path_Immutable.delete(my_dict, 'a.c')
# {
#   a: {
#     b: 'f'
#   }
# }

Can also delete a deep array item using splice

new_dict = Dict_Path_Immutable.delete(my_dict, 'a.c.0')
# {
#   a: {
#     b: 'f',
#     c: ['f']
#   }
# }

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for Dict-Path-Immutable, version 0.2
Filename, size File type Python version Upload date Hashes
Filename, size Dict_Path_Immutable-0.2-py3-none-any.whl (2.6 kB) File type Wheel Python version py3 Upload date Hashes View hashes
Filename, size Dict_Path_Immutable-0.2.tar.gz (1.7 kB) File type Source Python version None Upload date Hashes View hashes

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page