0

Here's the code I am using. I need to be able to change the value of test["test1"]["test2"]["test3"] from values contained in a list. This list could become longer or shorter. If the key doesn't exist I need to be able to create it.

test = {"test1": {"test2": {"test3": 1}}}

print test["test1"]["test2"]["test3"]
# prints 1

testParts = ["test1", "test2", "test3"]

test[testParts] = 2

print test["test1"]["test2"]["test3"]
# should print 2
1
  • The techniques in my answer there apply here too; use reduce() to walk to the innermost dictionary (creating additional dictionaries as needed). Commented Apr 11, 2014 at 12:34

1 Answer 1

1

When you try

test[testParts] = 2

you will get a TypeError, because testParts is a list, which is mutable and unhashable and therefore cannot be used as a dictionary key. You can use a tuple (immutable, hashable) as a key:

testParts = ("test1", "test2", "test3")
test[testParts] = 2

but this would give you

test == {('test1', 'test2', 'test3'): 2, 'test1': {'test2': {'test3': 1}}}

There is no built-in way to do what you are trying to do, i.e. "unpack" testParts into keys to nested dictionaries. You can either do:

test["test1"]["test2"]["test3"] = 2

or write a function to do this yourself.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I think this solves my issue. I'll mark the correct answer when I can.
The answer to Martijn's linked question covers a great approach to "writ[ing] a function to do this yourself".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.