【问题标题】:Nested Dict with get command带有 get 命令的嵌套字典
【发布时间】:2013-07-31 11:25:29
【问题描述】:

我正在尝试从 python 中的嵌套字典中获取值。问题是,当嵌套 dict 的父级不可用时,我希望它返回 None 或 Zero 但我猜我使用 get 的问题是已经返回 Nonetype ,因此当我使用时出现错误:

pl_map.get(item)["ref_rate"]

现在,当项目在 dict 中可用时,代码可以正常工作,但会引发 TypeError,因为 NoneType 对象不可订阅。

谁能告诉我如何解决这个问题,我已经粘贴了下面的某些部分代码。

从下面的函数中可以看出,基本上 pl_map 是一个嵌套的字典。对于我可能做出的任何遗漏,我深表歉意。

for item in sorted(iwb_map):
    for wh in sorted(iwb_map[item]):
        #webnotes.msgprint(pl_map.get(item,0))
        qty_dict = iwb_map[item][wh]
        data.append([item,item_map[item]["description"], wh,
            qty_dict.bal_qty,pl_map.get(item)["ref_rate"],0,0,item_map[item]["base_material"],
            item_map[item]["quality"], item_map[item]["tool_type"], 
            item_map[item]["height_dia"], item_map[item]["width"],
            item_map[item]["length"], item_map[item]["d1"],
            item_map[item]["l1"], item_map[item]["is_rm"],
            item_map[item]["brand"]

        ])

def get_pl_map(filters):
    if filters.get("pl"):
        conditions = " and price_list_name = '%s'" % filters["pl"]
    else:
        webnotes.msgprint("Please select a Price List for Valuation Purposes", raise_exception=1)

    pl_map_int = webnotes.conn.sql ("""SELECT it.name, p.price_list_name, p.ref_rate
        FROM `tabItem` it, `tabItem Price` p
        WHERE p.parent = it.name %s
        ORDER BY it.name""" % conditions, as_dict=1)
    pl_map={}

    for d in pl_map_int:
        pl_map.setdefault(d.name,d)
    #webnotes.msgprint(pl_map)
    return pl_map

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    让第一个 .get() 返回一个空字典作为默认值,然后在其上使用 .get():

    pl_map.get(item, {}).get("ref_rate")
    

    现在您将获得pl_map[item]['ref_rate'] 或None 的值。

    另一种方法是显式测试item:

    pl_map[item]['ref_rate'] if item in pl_map else None
    

    【讨论】:

    • 这只是救了我的命。
    【解决方案2】:

    一种可能性是使用defaultdict,这样每个不存在的密钥都会在首次​​访问时自动初始化:

    >>> from collections import defaultdict
    >>> pl_map = defaultdict(lambda: defaultdict(lambda: None))
    >>> pl_map["item"]["ref_rate"]    # returns None
    

    之后所有访问的键都将存在:

    >>> pl_map
    defaultdict(<function <lambda> at 0x40350af0>, {'item': defaultdict(<function <lambda> at 0x40350a30>, {'ref_rate': None})})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-12
      相关资源
      最近更新 更多