0

So I have an array like so ['test', 'testtwo'].

I wish to able to use that as an index for a dictionary like so myDict['test']['testtwo'].

Is this possible in python? Sorry for the short explanation.

EDIT:

exampleDict = {
  'test': {
    'testtwo': [
      '',
      ''
    ]
  }
}

And when doing some stuff in python I end up with the array ['test', 'testtwo'] and then need to use that to access exampleDict['test']['testtwo']. The keys change though and the number of keys in the array changes as well.

6
  • 3
    What is the bigger picture of what you want to achieve? a dictionary might be what you are looking for Commented Feb 17, 2017 at 14:58
  • yeah sorry both, I meant dictionary :/ Commented Feb 17, 2017 at 14:59
  • You mean, python dict Commented Feb 17, 2017 at 14:59
  • do you mean: __list=['test', 'testtwo']; mydict = {__list: "foo" }? Commented Feb 17, 2017 at 15:01
  • 1
    Can you show a sample dictionary? Commented Feb 17, 2017 at 15:02

2 Answers 2

2

You could either use a loop, iterating the indices in the list and updating the "current" dict as you go:

>>> exampleDict = {'test': {'testtwo': [ '', '']}}
>>> d = exampleDict                               
>>> for x in idx:
...     d = d[x]
>>> d
['', '']

Or you could even use reduce (functools.reduce in Python 3):

>>> reduce(lambda d, x: d[x], idx, exampleDict)
['', '']

You could use a similar approach to update the dict, but 1) you should use setdefault in case part of the index-list is not yet in the dict, and 2) you have to remove the last item from the list and use that as a regular index to the returned dictionary.

>>> idx2 = ['test', 'testthree', 'four']
>>> reduce(lambda d, x: d.setdefault(x, {}), idx2[:-1], exampleDict)[idx2[-1]] = "foo"
>>> exampleDict
{'test': {'testthree': {'four': 'foo'}, 'testtwo': ['', '']}}

In Python 3, you could make that line a bit easier to use using tuple-unpacking with *:

>>> *path, last = idx2
>>> reduce(lambda d, x: d.setdefault(x, {}), path, exampleDict)[last] = "foo"
Sign up to request clarification or add additional context in comments.

2 Comments

This works great, but how can I then update the original dictionary?
Thank you so much @tobias_k the last bit works like a charm!
2

You cannot use a list for a dictionary key because lists are mutable, and mutable keys aren't allowed, but I think that what you want is to use each element of the list as an index. Without more context, it's not easy to say whether this is a good idea without proper checks, but:

my_list = ['a', 'b']
my_dict[my_list[0]][my_list[1]] # access at ['a']['b']

I have a feeling that whichever problem you wish to solve might be solved in a different way.

2 Comments

Like this, but the number of keys in my_list changes so I can't type it out manually as you did in the second line.
@MattCowley Right, but I hard-coded the list for the sake of example. You will need to pre-populate your dictionary while you build the list so key accesses to the dictionary are valid. I wrote my answer before you provided additional information thogh. tobias_k's answer looks good for the dictionary updates I described.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.