[SOLVED] Replace underscore with whitespace in a list of list of dictionaries

Issue

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

Solution

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'}]]

Answered By – Henry Ecker

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.