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 9235145
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T06:57:26+00:00 2026-06-18T06:57:26+00:00

I have a complex dictionary structure which I would like to access via a

  • 0

I have a complex dictionary structure which I would like to access via a list of keys to address the correct item.

dataDict = {
    "a":{
        "r": 1,
        "s": 2,
        "t": 3
        },
    "b":{
        "u": 1,
        "v": {
            "x": 1,
            "y": 2,
            "z": 3
            },
        "w": 3
        }
    }    

maplist = ["a", "r"]

or

maplist = ["b", "v", "y"]

I have made the following code which works but I’m sure there is a better and more efficient way to do this if anyone has an idea.

# Get a given data from a dictionary with position provided as a list
def getFromDict(dataDict, mapList):    
    for k in mapList:
        dataDict = dataDict[k]
    return dataDict

# Set a given data in a dictionary with position provided as a list
def setInDict(dataDict, mapList, value): 
    for k in mapList[:-1]:
        dataDict = dataDict[k]
    dataDict[mapList[-1]] = value
  • 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-18T06:57:27+00:00Added an answer on June 18, 2026 at 6:57 am

    Use reduce() to traverse the dictionary:

    from functools import reduce  # forward compatibility for Python 3
    import operator
    
    def getFromDict(dataDict, mapList):
        return reduce(operator.getitem, mapList, dataDict)
    

    and reuse getFromDict to find the location to store the value for setInDict():

    def setInDict(dataDict, mapList, value):
        getFromDict(dataDict, mapList[:-1])[mapList[-1]] = value
    

    All but the last element in mapList is needed to find the ‘parent’ dictionary to add the value to, then use the last element to set the value to the right key.

    Demo:

    >>> getFromDict(dataDict, ["a", "r"])
    1
    >>> getFromDict(dataDict, ["b", "v", "y"])
    2
    >>> setInDict(dataDict, ["b", "v", "w"], 4)
    >>> import pprint
    >>> pprint.pprint(dataDict)
    {'a': {'r': 1, 's': 2, 't': 3},
     'b': {'u': 1, 'v': {'w': 4, 'x': 1, 'y': 2, 'z': 3}, 'w': 3}}
    

    Note that the Python PEP8 style guide prescribes snake_case names for functions. The above works equally well for lists or a mix of dictionaries and lists, so the names should really be get_by_path() and set_by_path():

    from functools import reduce  # forward compatibility for Python 3
    import operator
    
    def get_by_path(root, items):
        """Access a nested object in root by item sequence."""
        return reduce(operator.getitem, items, root)
    
    def set_by_path(root, items, value):
        """Set a value in a nested object in root by item sequence."""
        get_by_path(root, items[:-1])[items[-1]] = value
    

    And for completion’s sake, a function to delete a key:

    def del_by_path(root, items):
        """Delete a key-value in a nested object in root by item sequence."""
        del get_by_path(root, items[:-1])[items[-1]]
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have been working to build a complex data structure which would return a
I have a Dictionary<object1, List<object2> (a abstractisation I made for my structure, which is
I have two complex dictionaries in the form Dictionary<string, Dictionary<string, Dictionary<string, List<string>>>> So as
I have dictionary which I'm mapping using Fluent NHibernate. The dictionary has a complex
I have complex-type object of entity framework. I would like buid dynamically select and
My objects in a complex structure have a property Dictionary<Object, Object> Annotations , where
I have a Dictionary<Guid, ElementViewModel> . (ElementViewModel is our own complex type.) I add
I am using WCF and REST, and I have complex types, which are working
I have several complex data structures like Map< A, Set< B > > Set<
I have some complex regular expressions which I need to comment for readability and

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.