Skip to main content

Code to deeply merge multiple python dictionaries

Project description

This provides the option_merge.MergedOptions class, which allows you to treat multiple python dictionaries as one.

Documentation can be found at http://option-merge.readthedocs.org/

Usage

Either the classmethod shortcut:

options = MergedOptions.using(options1, options2)

Or with the update method:

options = MergedOptions()
options.update(options1)
options.update(options2)

And a separate override with __setitem__ syntax:

options['a'] = 1
options['b.c'] = 2
options['b'] = {"d": 3}
options[['b', 'e']] = 4

options.as_dict() == {"a": 1, "b.c": 2, "b": {"d": 3, "e": 4}}

When options are added, copies are made.

When you delete a key, it removes it from the first dictionary it can find. This means a key can change value when deleted rather than disappearing altogether

So:

options1 = {'a':{'b':1, 'c':3}, 'b':5}
options2 = {'a':{'b':4', 'c':9}, 'd':7}
options = MergedOptions.using(options1, options2)

# options['a'] == MergedOptions(prefix='a', <same_options>, <same_overrides>)
# options['a']['b'] == 4
# options['a']['c'] == 9
# options['d'] == 7

del options['a']['c']
# options['a']['c'] == 3

You may also get all values for a key with merged.values_for(path) where path is a dot-separated path. So options.values_for(“a.b”) == [4, 1]

You can also get all deeply nested keys with merged.all_keys(). So merged.all_keys() == [“d”, “a.b”, “b”, “a.c”]

Installation

Use pip!:

pip install option_merge

Or if you’re developing it:

pip install -e .
pip install -e ".[tests]"

Tests

Run the helpful script:

./test.sh

Project details


Download files

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

Source Distribution

option_merge-1.4.4.tar.gz (17.9 kB view details)

Uploaded Source

File details

Details for the file option_merge-1.4.4.tar.gz.

File metadata

  • Download URL: option_merge-1.4.4.tar.gz
  • Upload date:
  • Size: 17.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for option_merge-1.4.4.tar.gz
Algorithm Hash digest
SHA256 9681955cc314a23a06f911f8e3a82160d15ce6437990316f7f8a2053bc8981ea
MD5 43e47db3877deeb2a5053ddc9e5464eb
BLAKE2b-256 2f5711b1eb24c90f5812336d7d6cb38a104b6dbabff147872a30030cc8e1e0c6

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page