Combining Iterables with Fillvalue and OrderedDict

  • Share this:

Code introduction


This function accepts multiple iterable objects as arguments. If these objects are of different lengths, it uses fillvalue to fill the shorter iterable. It uses OrderedDict to maintain the insertion order and converts each tuple to a dictionary.


Technology Stack : itertools, collections

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    from itertools import zip_longest
    from collections import OrderedDict
    
    # 将多个可迭代对象合并为一个迭代器,如果某个可迭代对象较短,则以fillvalue填充
    combined = zip_longest(*args, fillvalue=fillvalue)
    
    # 使用OrderedDict来保持插入顺序,并转换每个元组为字典
    result = [OrderedDict(zip(args, item)) for item in combined]
    
    return result