Search code examples
pythonlocust

Locust/Python and using values from one list in another list


I have list 1:

TS_IDs = [
    '10158',
    '10159',
    '10174'
]

and list 2:

values = [
    {
        "id": 10017,
        "values": [
            {
                "from": "2022-10-30T12:00:00Z",
                "to": "2022-10-30T13:00:00Z",
                "value": 15
            },
            {
                "from": "2022-10-30T13:00:00Z",
                "to": "2022-10-30T14:00:00Z",
                "value": 16
            }
      ]
    }
]

I want to use values from list 1 into list 2 for the id-value (here being 10017).

How can that be obtained?


Solution

  • You are most likely looking for random.choice() assuming you want to assign a randomly selected item from TS_IDs to each item in values.

    import random
    import copy
    
    ## ---------------------------
    ## Just so we don't mutate values
    ## ---------------------------
    values_new = copy.deepcopy(values)
    ## ---------------------------
    
    for item in values_new:
        item["id"] = random.choice(TS_IDs)
    
    print(values_new)
    

    However, if you want to assign the ids randomly without duplication (assuming the length of values is less than the length of TS_IDs) you might use random.sample() or random.shuffle() on TS_IDs.

    import random
    import copy
    
    ## ----------------------
    ## get a random ordering of TS_IDs.
    ## random.sample() works as well but mutates TS_IDs
    ## ----------------------
    TS_IDs_new = random.sample(TS_IDs, len(TS_IDs))
    ## ----------------------
    
    ## ---------------------------
    ## Just so we don't mutate values
    ## ---------------------------
    values_new = copy.deepcopy(values)
    ## ---------------------------
    
    for index, item in enumerate(values_new):
        item["id"] = TS_IDs_new[index]
    
    print(values_new)
    

    If you want to just use TS_IDs in order then:

    import random
    import copy
    
    ## ---------------------------
    ## Just so we don't mutate values
    ## ---------------------------
    values_new = copy.deepcopy(values)
    ## ---------------------------
    
    for index, item in enumerate(values_new):
        item["id"] = TS_IDs[index]
    
    print(values_new)
    

    Note, you might want to place a guard against values having more items than TS_IDs in the last two cases.