Accessing elements of Python dictionary by index

后端 未结 10 1697
说谎
说谎 2020-11-22 08:52

Consider a dict like

mydict = {
  \'Apple\': {\'American\':\'16\', \'Mexican\':10, \'Chinese\':5},
  \'Grapes\':{\'Arabian\':\'25\',\'Indian\':\'20\'} }
         


        
10条回答
  •  粉色の甜心
    2020-11-22 09:22

    With the following small function, digging into a tree-shaped dictionary becomes quite easy:

    def dig(tree, path):
        for key in path.split("."):
            if isinstance(tree, dict) and tree.get(key):
                tree = tree[key]
            else:
                return None
        return tree
    

    Now, dig(mydict, "Apple.Mexican") returns 10, while dig(mydict, "Grape") yields the subtree {'Arabian':'25','Indian':'20'}. If a key is not contained in the dictionary, dig returns None.

    Note that you can easily change (or even parameterize) the separator char from '.' to '/', '|' etc.

提交回复
热议问题