Home > OS >  Replace underscore with whitespace in a list of list of dictionaries
Replace underscore with whitespace in a list of list of dictionaries

Time:02-26

I'm trying to replace every underscore '_' by a whitespace in a list of a list of a dictionary using this code:

d=[[{"30": "PRIORITY"}, {"2022:02:25-12:06:09": "TIMESTAMP"}, {"tester": "HOSTNAME"}, {"named": "APPNAME"}, {"3456": "PID"}, {"resolver_priming_query_complete": "ACTION"}]]
f=''
def Regler(d):
    for i in d:
        for j in i:
            for k in j.keys():
                if('_' in k):
                    k=k.replace('_', ' ')
                    print(d)
Regler(d)

What I want as an output is the same input, but just replace the underscore with a space, I'm not sure where what I missed in my code

CodePudding user response:

It's better just to write a new version of dictionary instead of modifying the existing one

d=[[{"30": "PRIORITY"}, {"2022:02:25-12:06:09": "TIMESTAMP"}, {"tester": "HOSTNAME"}, {"named": "APPNAME"}, {"3456": "PID"}, {"resolver_priming_query_complete": "ACTION"}]]
f=''
def Regler(d):
    modified_input = []
    for i in d:
        for j in i:
            temp_dict = {}
            for k, value in j.items():
                if('_' in k):
                    k=k.replace('_', ' ')
                temp_dict[k] = value
            modified_input.append(temp_dict)
        return [modified_input]

print(Regler(d))

CodePudding user response:

List comprehensions and dictionary comprehensions are designed to build lists and dictionaries.

We can build a new dictionary (without underscores) for each dictionary in each sublist of the list of lists:

def regler(lst_of_lst):
    return [
        [
            # Build dictionary with out underscores in key
            {k.replace('_', ' '): v for k, v in d.items()}
            for d in sublist
        ]
        for sublist in lst_of_lst
    ]

With the sample test:

d = [[{"30": "PRIORITY"}, {"2022:02:25-12:06:09": "TIMESTAMP"},
      {"tester": "HOSTNAME"}, {"named": "APPNAME"}, {"3456": "PID"},
      {"resolver_priming_query_complete": "ACTION"}]]

print(regler(d))

Output:

[[{'30': 'PRIORITY'},
  {'2022:02:25-12:06:09': 'TIMESTAMP'},
  {'tester': 'HOSTNAME'},
  {'named': 'APPNAME'},
  {'3456': 'PID'},
  {'resolver priming query complete': 'ACTION'}]]
  • Related