代码之家  ›  专栏  ›  技术社区  ›  Rovanion

有像Clojure的get-in这样的python函数吗?

  •  0
  • Rovanion  · 技术社区  · 6 年前

    在Python中是否有与Clojure的get-in函数等价的东西?它获取某个数据结构中给定路径处的数据。

    在Clojure中,它的用法如下:

    (def employee
      {:name "John"
       :details {:email "info@domain.com"
                 :phone "555-144-300"}})
    
    (get-in employee [:details :email])  ; => "info@domain.com"
    

    如果翻译成Python语法,它的用法如下:

    dictionary = {'a': {'b': 10}}
    get_in(dictionary, ['a', 'b'])  # => 10
    

    此函数用于访问嵌套数据结构中的任意数据点,其中路径在编译时未知,它们是动态的。更多使用示例 get-in 可以在上找到 clojuredocs

    3 回复  |  直到 6 年前
        1
  •  1
  •   Aleph Aleph    6 年前

    你可以写:

    dictionary.get('details', {}).get('email')
    

    这将安全地获得您需要的价值,或者 None ,没有抛出异常-就像Clojure的 get-in 做。

    def get_in(d, keys):
        if not keys:
            return d
        elif len(keys) == 1:
            return d.get(keys[0])
        else:
            return get_in(d.get(keys[0], {}), keys[1:])
    
        2
  •  2
  •   FHTMitchell    6 年前

    不,但你可以做一个

    def get_in(d, keys):
       if not keys:
           return d
       return get_in(d[keys[0]], keys[1:])
    
        3
  •  0
  •   Sushant    6 年前

    x = {'a':{'b':{'c': 1}}}
    
    def get_element(elements, dictionary):
        for i in elements:
            try:
                dictionary = dictionary[i]
            except KeyError:
                return False
        return dictionary
    
    print(get_element(['a', 'b', 'c'], x))
    # 1
    print(get_element(['a', 'z', 'c'], x))
    # False