代码之家  ›  专栏  ›  技术社区  ›  Rohan Monga

一种优雅的解决方案,用于在具有易变结构的json哈希上循环

  •  2
  • Rohan Monga  · 技术社区  · 14 年前

    我有一个json散列,它有很多键。我定期从web服务中检索这个散列,并针对不同的参数等进行检索。这或多或少有固定的结构,即有时会丢失密钥。 所以我最终得到了很多如下性质的代码

    编辑: 样品 data

    data =
    {
    id1 : {dict...},
    id2 : {dict..},
    '' : {value...},
    ...
    }
    
    for item in data:
       id = data.get("id")
       if not id:
          continue
       ...
    

    数据 dict 我在每一个巢穴里循环。这里也缺少钥匙:(

    我想知道有没有比50种不同的 if s和 continue s

    1 回复  |  直到 14 年前
        1
  •  1
  •   pyfunc    14 年前

    迭代dict键并进行处理如何:

    data = {
    'id1' : {'a':"", 'b':""},
    'id2' : {'c':"", 'd':""},
    '' : {'c':"", 'd':""},
    "": {'c':"", 'd':""},
    }
    
    for key in data.iterkeys():
        if key:
            print key
            print "Processing %s" % key
            # do further processing of data[key]
    

    这将输出以下内容。请注意,它跳过了缺少密钥的处理。

    id2
    Processing id2
    id1
    Processing id1