获取未知深度的任意字典中的键值

时间:2012-03-28 18:36:45

标签: python json dictionary

我有一本未知深度和结构的字典。它可能包含更多字典,字典列表等。它是通过反序列化由另一个系统创建的一些JSON输入创建的。在该词典的不同位置有一个键,可能是多个具有相同名称的键。我想获取每个键的值,并理想地更新它们。

给定这样的目录结构:

{
  "tags":{
    "social-1":{
      "email":True,
      "twitter":True,
      "facebook":True,
      "linkedin":True,
      "type":"social"
    },
    "primary":{
      "type":"flexible",
      "width":"auto",
      "blocks":[
        {
          "type":"combo",
          "data":{
            "styles":{
              "margin":"10",
              "padding":"0",
              "borderColor":"#000",
              "borderWidth":"0",
              "borderStyle":"solid",
              "backgroundColor":"transparent",
              "width":"auto"
            },
            "placeholder":True,
            "headline":{
              "visible":False
            },
            "subHeadline":{
              "visible":False
            },
            "imageHolder":{
              "visible":True,
              "value":[
                {
                  "url":None,
                  "caption":None,
                  "width":220,
                  "height":140,
                  "padding":10,
                  "alt":"",
                  "href":None,
                  "filePath":None,
                  "sizing":"original",
                  "source":"disk",
                  "displayWidth":200,
                  "displayHeight":140,
                  "displayPadding":{
                    "left":10,
                    "top":0,
                    "right":10,
                    "bottom":10
                  }
                }
              ],
              "smartSizing":True,
              "captions":False,
              "captionDefault":None
            },
            "content":{
              "visible":True,
              "value":"<p>Your text here.</p>"
            },
            "imagePosition":"left",
            "textWrap":False,
            "type":"combo"
          }
        },
        {
          "type":"image",
          "data":{
            "styles":{
              "margin":"10",
              "padding":"0",
              "borderColor":"#000",
              "borderWidth":"0",
              "borderStyle":"solid",
              "backgroundColor":"transparent",
              "width":"auto"
            },
            "placeholder":False,
            "imageHolder":[
              {
                "url":None,
                "caption":None,
                "width":0,
                "height":140,
                "padding":10,
                "alt":"",
                "href":None,
                "filePath":None,
                "sizing":"original",
                "source":"disk",
                "displayWidth":213,
                "displayHeight":159,
                "displayPadding":{
                  "left":10,
                  "top":10,
                  "right":5,
                  "bottom":10
                }
              },
              {
                "url":None,
                "caption":None,
                "width":0,
                "height":140,
                "padding":10,
                "alt":"",
                "href":None,
                "filePath":None,
                "displayWidth":213,
                "displayHeight":159,
                "source":"disk",
                "sizing":"original",
                "displayPadding":{
                  "left":5,
                  "top":10,
                  "right":5,
                  "bottom":10
                }
              },
              {
                "url":None,
                "caption":None,
                "width":0,
                "height":140,
                "padding":10,
                "alt":"",
                "href":None,
                "filePath":None,
                "displayWidth":213,
                "displayHeight":159,
                "source":"disk",
                "sizing":"original",
                "displayPadding":{
                  "left":5,
                  "top":10,
                  "right":10,
                  "bottom":10
                }
              }
            ],
            "orientation":"horizontal",
            "smartSizing":True,
            "captions":False,
            "captionDefault":None,
            "type":"image"
          }
        }
      ]
    }
  }
}

我如何检查和更新imageHolder键的值?

3 个答案:

答案 0 :(得分:5)

您可以使用递归函数降序列表和字典值:

def get_all(data, key):
    sub_iter = []
    if isinstance(data, dict):
        if key in data:
            yield data[key]
        sub_iter = data.itervalues()
    if isinstance(data, list):
        sub_iter = data
    for x in sub_iter:
        for y in get_all(x, key):
            yield y

答案 1 :(得分:4)

递归地遍历树结构以找到您关心的元素。 E.g:

>>> def process(blob):
...     for (k,v) in blob.items():
...         if k == 'imageHolder':
...             ...do-something...
...         if isinstance(v, dict):
...             process(v)

if isinstance(v,dict):行可能会替换为各种替代方案,具体取决于您对输入的期望 - 例如,您可以使用if hasattr(v, 'items')之类的内容进行欺骗。

答案 2 :(得分:1)

你需要递归:

    def search_key(mykey, mydict):
        if isinstance(mydict, dict):
            for key, value in mydict.items():
                search_key(mykey, value)
            if mykey in mydict:
                print 'found old_value=%r' % mydict[mykey]
                mydict[mykey]='foo' # update
        elif isinstance(mydict, (list, tuple)):
            for value in mydict:
                search_key(mykey, value)
    search_key('imageHolder', mydict)
    mydict={...} # your long json structure
    search_key('imageHolder', mydict)