daily pastebin goal
20%
SHARE
TWEET

Untitled

a guest Nov 23rd, 2017 54 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from collections import abc
  2.  
  3.  
  4. def get_from_nested(dic, keys=None, default=None):
  5.     """
  6.     >>> get_from_nested({'hoge': {'fuga': 1}}, keys=['hoge'], default=[])
  7.     {'fuga': 1}
  8.     >>> get_from_nested({'hoge': {'fuga': 1}}, keys=['hoge', 'fuga'], default=[])
  9.     1
  10.     >>> get_from_nested({'hoge': {'fuga': 1}}, keys=['hoge', 'fuga', 'yeah'], default=[])
  11.     []
  12.     >>> get_from_nested({}, keys=['hoge', 'fuga', 'yeah'], default=[])
  13.     []
  14.     >>> get_from_nested({'hoge': {'fuga': 1}}, keys=[])
  15.     >>> get_from_nested({'hoge': {'fuga': 1}})
  16.     """
  17.     keys = keys or []
  18.     if keys:
  19.         head, *tail = list(keys)
  20.         value = dic.get(head, default)
  21.         if isinstance(value, abc.Mapping) and tail:
  22.             return get_from_nested(value, tail, default=default)
  23.         elif tail:
  24.             # キーは続いてるけどすでに値が見つかってる
  25.             return default
  26.         else:
  27.             return value
  28.     else:
  29.         return default
  30.  
  31. if __name__=='__main__':
  32.     import doctest
  33.     doctest.testmod()
RAW Paste Data
Top