Loop through all nested dictionary values?

前端 未结 12 1258
温柔的废话
温柔的废话 2020-11-22 09:16
for k, v in d.iteritems():
    if type(v) is dict:
        for t, c in v.iteritems():
            print \"{0} : {1}\".format(t, c)

I\'m trying to l

12条回答
  •  太阳男子
    2020-11-22 10:02

    I am using the following code to print all the values of a nested dictionary, taking into account where the value could be a list containing dictionaries. This was useful to me when parsing a JSON file into a dictionary and needing to quickly check whether any of its values are None.

        d = {
                "user": 10,
                "time": "2017-03-15T14:02:49.301000",
                "metadata": [
                    {"foo": "bar"},
                    "some_string"
                ]
            }
    
    
        def print_nested(d):
            if isinstance(d, dict):
                for k, v in d.items():
                    print_nested(v)
            elif hasattr(d, '__iter__') and not isinstance(d, str):
                for item in d:
                    print_nested(item)
            elif isinstance(d, str):
                print(d)
    
            else:
                print(d)
    
        print_nested(d)
    

    Output:

        10
        2017-03-15T14:02:49.301000
        bar
        some_string
    

提交回复
热议问题