Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{'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]}

>Solution :

You can get the desired output on the defined input by just changing the iterator order like below

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(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)

Output:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading