Iterate over nested dictionary

后端 未结 5 1908
孤城傲影
孤城傲影 2020-11-30 02:24

Is there an easy way of iterating over nested dictionary, which may consist of other objects like lists, tuples, then again dictionaries so that iteration covers all the ele

5条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 03:13

    Iterating over a nested dictionary containing unexpected nested elements.

    Here is my solution :

    # d is the nested dictionary
    
    for item in d:
        if type(item) == list:
            print "Item is a list"
            for i in item: print i
        elif type(item) == dict:
            print "Item is a dict"
            for i in item: print i
        elif type(item) == tuple:
            print "Item is a tuple"
            for i in item: print i
        else:
            print "Item is not a list, neither a dict and not even a tuple"
            print item
    

    I think the above example is very general, you can mold it for your use case.

提交回复
热议问题