Skip to content
Advertisement

Fill in empty value in dictionary based on matching value in separate dictionary (Python)

I am trying to output a dictionary that fills in values already defined by another dictionary. The values that have not been defined return false. However my output is not the order it should be in.

Code:

route1 = {
    'RouteID': 1,
    'StepID': [1, 2, 3, 4],
    'StepName': ['104-1', '104-2', '105-A', '105-B'],
    'Direction': ['Left', 'Right', 'Right', 'Left']}

route2 = {
    'RouteID': 2,
    'StepID': [1, 2, 3, 4],
    'StepName': ['104-2', '105-A', '105-C', '105-D'],
    'Direction': []}

def routeMapper(longRoute, subRoute):
    for i, v in enumerate(longRoute['StepName']):
        found = False
        for j, b in enumerate(subRoute['StepName']):
            if v == b:
                found = True
                subRoute['Direction'].append(longRoute['Direction'][i])
        if not found:
            subRoute['Direction'].append(False)

routeMapper(route1, route2)
print(route2)

Output:

{'RouteID': 2, 'StepID': [1, 2, 3, 4], 'StepName': ['104-2', '105-A', '105-C', '105-D'], 'Direction': [False, 'Right', 'Right', False]}

The Output I am looking for (in the ‘Direction’ key):

{'RouteID': 2, 'StepID': [1, 2, 3, 4], 'StepName': ['104-2', '105-A', '105-C', '105-D'], 'Direction': ['Right', 'Right', False, False]}

Advertisement

Answer

Since you enumerate through longRoute first, the order of subRoute['Direction'] will depend on the order of longRoute['StepName'] instead of subRoute['StepName'].

Just loop through subRoute first to preserve the order, then compare against longRoute.

def routeMapper(longRoute, subRoute):
for i, v in enumerate(subRoute['StepName']):
    found = False
    for j, b in enumerate(longRoute['StepName']):
        if v == b:
            found = True
            subRoute['Direction'].append(longRoute['Direction'][j])
    if not found:
        subRoute['Direction'].append(False)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement