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
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
TechnoCF
  • 178
  • 1
  • 8
  • The techniques in my answer there apply here too; use reduce() to walk to the innermost dictionary (creating additional dictionaries as needed). – Martijn Pieters Apr 11 '14 at 12:34

1 Answers1

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.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437