-1

I use Python 3.9 and I have a problem, I have a list:

keyList = ['a', 'b', 'c', 'd']

and I have a dictionary too, and I want to edit (update) this dictionary in the following way:

myDict = {}
#some code to add the keyList to myDict, this is my question, because I don't know...
myDict = {'a' : {'b' : {'c' : {'d' : 1}}}}

#or when myDict isn't equal to {}

myDict = {'a' : {'c' : 1}}
#same code to add the keyList to myDict
myDict = {'a' : {'c' : 1, 'b' : {'c' : {'d' : 1}}}}
#same code to add the keyList to myDict, but when it is created, add the +1 to value:
myDict = {'a' : {'c' : 1, 'b' : {'c' : {'d' : 2}}}}
Nohab
  • 39
  • 6
  • 3
    It would be an interesting challenge to write this question in a more obscure and puzzling manner. Suggestion: try to rephrase it. –  Feb 06 '22 at 09:48
  • And do you really, really want deeply nested dict? – buran Feb 06 '22 at 09:56
  • buran: Yes, is there any way to do this? – Nohab Feb 06 '22 at 09:58
  • bbbbbbbbb: I tried to rephrase it, now? – Nohab Feb 06 '22 at 09:59
  • It appears that you want a `dict` subclass that's a mix of nesting dictionaries but acts like a [Counter](https://docs.python.org/3/library/collections.html#collections.Counter) as well. What should happen after the last line if you 'add a keylist' of [a,b,c,d,e]? – kcsquared Feb 06 '22 at 10:06
  • @kcsquared counter is like a dictionary, no? So, how can I create a deeply nested counter or dictionary? – Nohab Feb 06 '22 at 10:21
  • This seems very, very similar to a [Trie](https://en.wikipedia.org/wiki/Trie), where your terminal nodes contain a frequency count. It's possible that a [standalone Trie class](https://stackoverflow.com/questions/11015320/how-to-create-a-trie-in-python) fits your use case, if you want to search for keylists or prefixes. – kcsquared Feb 06 '22 at 10:31

1 Answers1

1

IIUC, you could use dict.setdefault iteratively:

def update_myDict(myDict):
    d = myDict
    for k in keyList:
        if k == keyList[-1]:
            d[k] = d.get(k, 0) + 1
        else:
            d = d.setdefault(k, {})
    return myDict

Output:

>>> update_myDict({})
{'a': {'b': {'c': {'d': 1}}}}

>>> update_myDict({'a' : {'c' : 1}})
{'a': {'c': 1, 'b': {'c': {'d': 1}}}}

>>> update_myDict({'a' : {'c' : 1, 'b' : {'c' : {'d' : 1}}}}) 
{'a': {'c': 1, 'b': {'c': {'d': 2}}}}