Search code examples
pythonjsonregexlambdapython-itertools

How do I replace a single word repeated multiple times with a word from list?


What I have tried so far seems to

node_id = {'method': 'date','method': 'nodeid', 'id': serial_number}
    date = {'method': 'date'}
    frequency = {'method': 'freq', 'id':serial_number}
    bandwidth = {'method': 'bw' , 'id':serial_number}

Solution

  • Here is sample code using the first three values of level_1_methods:

    level_1_methods  = [
      {"result": ["51485"], "id": "51485", "jsonrpc": "2.0"},
      {"result": ["1515106787"], "jsonrpc": "2.0"},
      {"result": ["2240"], "id": "51485", "jsonrpc": "2.0"}
    ]
    
    level_1_methods_lst = ['node_id', 'date', 'frequency']
    
    for i in range(len(level_1_methods)):
      key = level_1_methods_lst[i]
      value = level_1_methods[i]['result']
    
      level_1_methods[i][key] = value
      level_1_methods[i].pop('result')
    
      print(level_1_methods[i])
    
    
    >>> {'id': '51485', 'jsonrpc': '2.0', 'node_id': ['51485']}
    >>> {'date': ['1515106787'], 'jsonrpc': '2.0'}
    >>> {'id': '51485', 'frequency': ['2240'], 'jsonrpc': '2.0'}
    

    You will need to change level_1_methods from a tuple to a list. Additionally, the outputted dictionary is ordered alphabetically which shouldn't make a difference if you ever need to extract the information. I hope this helps.