Search code examples
pythondictionaryrobotframework

How to dynamically apply variables to the values of a dictionary using Python and/or RobotFramework


Say I have a list of dictionaries:

URL_LIST = [
    {'google': 'http://www.google.com/join'},
    {'yahoo':  'http://www.yahoo.com/{0}/join'},
    {'msn':    'http://www.msn.com/{0}/join'}
]

Now, I want to pass this dictionary to a python function, along with two other variables, so that the two variables replaces the {0}s in the 'yahoo' and 'msn' variables:

def apply_arguments (url_list, yahoo_subpage, msn_subpage):
    #Do stuff
    return url_list

So if the yahoo_suboage = 'aaa' and msn_subpage = 'bbb', I want the final result to be like this:

URL_LIST = [
    {'google': 'http://www.google.com/join'},
    {'yahoo':  'http://www.yahoo.com/aaa/join'},
    {'msn':    'http://www.msn.com/bbb/join'}
]

I want to do it using either python or RobotFramework. Is that even possible?


Solution

  • I think your URL_LIST is unnecessarily nested, so I use a list in this answer.

    lst = [
        'http://www.google.com/join',
        'http://www.yahoo.com/{0}/join',
        'http://www.msn.com/{0}/join',
    ]
    
    dct = {
        'yahoo': 'aaa',
        'msn': 'bbb',
    }
    
    def make_changes(lst, dct):
    
        for i, url in enumerate(lst):
            k = url.split('.')[1]
            
            try:
                lst[i] = url.replace('{0}', dct[k])
            except:
                pass
                
        return lst
         
    
    print(make_changes(lst, dct))
    

    Output:

    ['http://www.google.com/join', 'http://www.yahoo.com/aaa/join', 'http://www.msn.com/bbb/join']