What is the best way to implement nested dictionaries?

后端 未结 21 2160
[愿得一人]
[愿得一人] 2020-11-22 00:29

I have a data structure which essentially amounts to a nested dictionary. Let\'s say it looks like this:

{\'new jersey\': {\'mercer county\': {\'plumbers\':          


        
21条回答
  •  半阙折子戏
    2020-11-22 00:49

    I have a similar thing going. I have a lot of cases where I do:

    thedict = {}
    for item in ('foo', 'bar', 'baz'):
      mydict = thedict.get(item, {})
      mydict = get_value_for(item)
      thedict[item] = mydict
    

    But going many levels deep. It's the ".get(item, {})" that's the key as it'll make another dictionary if there isn't one already. Meanwhile, I've been thinking of ways to deal with this better. Right now, there's a lot of

    value = mydict.get('foo', {}).get('bar', {}).get('baz', 0)
    

    So instead, I made:

    def dictgetter(thedict, default, *args):
      totalargs = len(args)
      for i,arg in enumerate(args):
        if i+1 == totalargs:
          thedict = thedict.get(arg, default)
        else:
          thedict = thedict.get(arg, {})
      return thedict
    

    Which has the same effect if you do:

    value = dictgetter(mydict, 0, 'foo', 'bar', 'baz')
    

    Better? I think so.

提交回复
热议问题