Search code examples
pythondictionaryfinite-automata

Automatic in python


I've been working on an automator in python, but I'm having some trouble creating a schematic.

If the input data is (where EV is even and OD is odd):

 EV|0|EV|1|OD
 OD|0|OD|1|EV

I'm trying to create a dictionary based schematic, such that for both even and odd, there are nested dictionaries

Though I'm having a lot of trouble coming up with ideas


Solution

  • How about this:

    data = 'EV|0|EV|1|OD;OD|0|OD|1|EV'
    
    # output: {even: {0:even, 1:odd}, odd: {0:odd, 1:even}}
    
    information = data.split(';')
    output = {}
    for piece in information:  # Each piece is like EV|0|EV|1|OD
        parts = piece.split('|')
        head = parts[0]  # Our dictionary key, eg. [EV]
        tail = parts[1:]  # Stuff that makes up the inner dict, e.g. [0, EV, 1, OD]
    
        # Use step = 2 to get key:value pairs from tail:
        inner = {tail[i]: tail[i+1] for i in range(0, len(tail)-1, 2)}
    
        if head not in output:
            output[head] = inner
        else:
            # What do we do here?
            pass
    
    print(output)
    

    Yields: {'EV': {'1': 'OD', '0': 'EV'}, 'OD': {'1': 'EV', '0': 'OD'}}

    If you wanted, at the very beginning, you could do:

    data = data.replace('EV', 'even').replace('OD', 'odd')