Search code examples
pythonlistconcatenation

Concatenate index of a list into a string variables


I have a list

list = ['1a-b2', '2j-u3', '5k-hy', '1h-j3']

and I have a string like below

main = '{"datatype: null" "country_code":"eu","offset":0,"id":"2y-9k"}'

How can I replace the id value in string, with its respective index in the master list ?

For Eg., I want to replace the "1h-j3" in the main string with its index in list. This to be done in a loop for all as well.

I have tried to concatenate using +, % but they did not work, kindly help me with this. Both the list indexes and main variable are of data type string

expected output is as follows in first loop

main = '{"datatype: null" "country_code":"eu","offset":0,"id":"1a-b2"}'

in second loop

main = '{"datatype: null" "country_code":"eu","offset":0,"id":"2j-u3"}'

in third loop

main = '{"datatype: null" "country_code":"eu","offset":0,"id":"5k-hy"}'

and so on


Solution

  • Well, I can think of 2 approaches, based on the type of data you have for the main variable. See below.

    In case, the value is a proper JSON

    import json
    
    items_list = ['1a-b2', '2j-u3', '5k-hy', "1h-j3"]
    # if main_dict was a valid json
    main_dict = json.loads('{"datatype": "null", "country_code":"eu","offset":0,"id":"1h-j3"}')
    main_dict["id"] = items_list.index(main_dict["id"])
    main_dict = json.dumps(main_dict)
    

    Other case, its a dirty string manipulation. May be there are better ways,

    # If its not a valid JSON
    str_main = '{"datatype: null" "country_code":"eu","offset":0,"id":"1h-j3"}'
    import re
    
    # Use a regex to find the key for replacement.
    found = re.findall(r'"id":".*"', str_main, re.IGNORECASE)
    if found and len(found) > 0:
        key = found[0].split(":")[1].replace('"', '')
        _id = items_list.index(key)
        str_main = str_main.replace(key, str(_id))
    
    print(str_main)
    

    produced output

    {"datatype: null" "country_code":"eu","offset":0,"id":"3"}
    

    --UPDATE--

    As per your requirement updated in question, then it will be a simple loop I assume like below.

    items_list = ['1a-b2', '2j-u3', '5k-hy', "1h-j3"]
    base_str = '{"datatype: null" "country_code":"eu","offset":0,"id":"_ID_"}'
    for item in items_list:
         main = base_str.replace('_ID_', item)
         print(main)
    

    Produces output like

    {"datatype: null" "country_code":"eu","offset":0,"id":"1a-b2"}
    {"datatype: null" "country_code":"eu","offset":0,"id":"2j-u3"}
    {"datatype: null" "country_code":"eu","offset":0,"id":"5k-hy"}
    {"datatype: null" "country_code":"eu","offset":0,"id":"1h-j3"}