python ordered dict with duplicates keys

前端 未结 1 2006
隐瞒了意图╮
隐瞒了意图╮ 2021-01-21 18:53

I\'m trying to write some python functions to generate a batch of input files, in which there is, for instance, this block:

***behavior
**energy_phase_1
ef_v 10
         


        
1条回答
  •  囚心锁ツ
    2021-01-21 18:58

    The concept of duplicate key goes against the concept of dict.

    If you need to maintain order and have duplicate keys I'd say you need to use another data structure. One possible solution would be using a list of tuples. Something like the following:

    inp = list()
    
    # Define your input as a list of tuples instead of as a dict
    
    inp.append(('***behavior', ('', '')))
    inp.append(('**energy_phase_1', ('', '')))
    inp.append(('**ef_v', ('10', '20')))
    inp.append(('**energy_phase_2', ('', '')))
    inp.append(('**ef_v', ('7', '14')))
    
    # You can have duplicate keys on the list and the order is preserved
    
    output = "\n".join(["{key} {val}".format(key=t[0], val=t[1][0]).strip() for t in inp])
    

    In this case the output variable would contain:

    ***behavior
    **energy_phase_1
    **ef_v 10
    **energy_phase_2
    **ef_v 7
    

    If you need to access values by key (a dict-like functionality) you could use something like this:

    def get_key_values(inp, key):
    
        filtr_by_key = filter(lambda t: True if t[0] == key else False, inp)
        return filtr_by_key
    
    ef_v_values = get_key_values(inp, "**ef_v")
    

    In this case the ef_v_values would contain only the values associated with the key **ef_v:

    [('**ef_v', ('10', '20')), ('**ef_v', ('7', '14'))]
    

    Hope this helps.

    0 讨论(0)
提交回复
热议问题