Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8380073
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T16:21:46+00:00 2026-06-09T16:21:46+00:00

How would you modify/create keys/values in a dict of nested dicts based on the

  • 0

How would you modify/create keys/values in a dict of nested dicts based on the values of a list, in which the last item of the list is a value for the dict, and the rest of items reefer to keys within dicts?
This would be the list:

list_adddress = [ "key1", "key1.2", "key1.2.1", "value" ]

This would only be a problem in situations like when parsing command line arguments. It’s obvious that modifying/creating this value within a script would be pretty easy using dict_nested["key1"]["key1.2"]["key1.2.1"]["value"].

This would be a nested dict of dicts:

dict_nested = { 
    "key1": {
                "key1.1": { 
                            "...": "...",
                },
                "key1.2": { 
                            "key1.2.1": "change_this",
                },
            },

    "key2": {
                "...": "..."
            },
}

I guess that in this case, something like a recursive function or a list comprehension would be required.

def ValueModify(list_address, dict_nested):
    ...
    ...
    ValueModify(..., ...)

Also, if items in list_address would reefer to keys in non-existing dictionaries, they should be created.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T16:21:48+00:00Added an answer on June 9, 2026 at 4:21 pm

    One-liner:

    keys, (newkey, newvalue) = list_address[:-2], list_address[-2:]
    reduce(dict.__getitem__, keys, dict_nested)[newkey] = newvalue
    

    Note: dict.get and operator.getitem would produce wrong exceptions here.

    An explicit for-loop as in Joel Cornett’s answer might be more readable.

    If you want to create non-existing intermediate dictionaries:

    reduce(lambda d,k: d.setdefault(k, {}), keys, dict_nested)[newkey] = newvalue
    

    If you want to override existing intermediate values that are not dictionaries e.g., strings, integers:

    from collections import MutableMapping
    
    def set_value(d, keys, newkey, newvalue, default_factory=dict):
        """
        Equivalent to `reduce(dict.get, keys, d)[newkey] = newvalue`
        if all `keys` exists and corresponding values are of correct type
        """
        for key in keys:
            try:
                val = d[key]
            except KeyError:
                val = d[key] = default_factory()
            else:
                if not isinstance(val, MutableMapping):
                    val = d[key] = default_factory()
            d = val
        d[newkey] = newvalue
    

    Example

    list_address = ["key1", "key1.2", "key1.2.1", "key1.2.1.1", "value"]
    dict_nested = {
        "key1": {
                    "key1.1": {
                                "...": "...",
                    },
                    "key1.2": {
                                "key1.2.1": "change_this",
                    },
                },
    
        "key2": {
                    "...": "..."
                },
    }
    
    set_value(dict_nested, list_address[:-2], *list_address[-2:])
    assert reduce(dict.get, list_address[:-1], dict_nested) == list_address[-1]
    

    Tests

    >>> from collections import OrderedDict
    >>> d = OrderedDict()
    >>> set_value(d, [], 'a', 1, OrderedDict) # non-existent key
    >>> d.items()
    [('a', 1)]
    >>> set_value(d, 'b', 'a', 2) # non-existent intermediate key
    >>> d.items()
    [('a', 1), ('b', {'a': 2})]
    >>> set_value(d, 'a', 'b', 3) # wrong intermediate type
    >>> d.items()
    [('a', {'b': 3}), ('b', {'a': 2})]
    >>> d = {}
    >>> set_value(d, 'abc', 'd', 4)
    >>> reduce(dict.get, 'abcd', d) == d['a']['b']['c']['d'] == 4
    True
    >>> from collections import defaultdict
    >>> autovivify = lambda: defaultdict(autovivify)
    >>> d = autovivify()
    >>> set_value(d, 'abc', 'd', 4)
    >>> reduce(dict.get, 'abcd', d) == d['a']['b']['c']['d'] == 4
    True
    >>> set_value(1, 'abc', 'd', 4) #doctest:+IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
    ...
    TypeError:
    >>> set_value([], 'abc', 'd', 4) #doctest:+IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
    ...
    TypeError:
    >>> L = [10]
    >>> set_value(L, [0], 2, 3)
    >>> L
    [{2: 3}]
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have to create a Windows Form application which would modify the connection sring
How would I modify this code to show the animated movement (item moving from
My application allows users to create and modify files. I would like them to
I want to create a custom IconItemRenderer for List, which looks something similar to
How would I modify the order email so that it adds the file to
I would like modify HTML like I am <b>Sadi, novice</b> programmer. to I am
I have the line of code below... How would I modify it to insert
I would like to modify an object private variable class Example(): __myTest1 = 1
We have a customer that would like to modify application user messages that we
I'm absolutely new to JavaScript and would like to modify a textarea of a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.