Alin G.
Alin G.

Reputation: 45

Replace one character in a list of dictionaries and return object to original format

I have a list of dictionaries that I'm trying to write to excel using ExcelWriter. This list of dictionaries is downloaded and formatted from an API I'm using.

Problem is that there are some items in those dictionaries that start with "=" and when exporting to Excel, the "=" is seen as a formula and the Excel becomes corrupted.

Is there any way to replace the "=" sign with, let's say, "-" in this list of dictionaries?

The list looks something like:

[{'name': 'allen', 'ticketid': '1', 'statement':'= sign not working'}, {'name': 'bob', 'ticketid': '2', 'statement': 'led should be green when up'}]

I would like to be able to replace that "=" sign with another character, maybe even write "equal" instead.

Thanks, A.

Upvotes: 1

Views: 41

Answers (3)

Berkin Anık
Berkin Anık

Reputation: 143

As Michael said, you should first iterate through your list to obtain your dictionaries and then you should iterate through your dictionaries inside your list as key, value indices.

Rather than replacing if it starts with "=" you can simply replace every "=" with what ever you want. As well as any other thing you would like to replace.

Your code should look like this:

your_list= [{'name': 'allen', 'ticketid': '1', 'statement':'= sign not working'}, {'name': 'bob', 'ticketid': '2', 'statement': 'led should be green when up'}]

for dict_in_list in your_list:
    for key, value in dict_in_list.items():
        dict_in_list[key] = value.replace("=", "your_replacement_goes_here")

After this tiny loop, any "=" inside your dictionaries' values would be replaced with what ever you want instead of "="

Upvotes: 1

pratham powar
pratham powar

Reputation: 25

Same what Michael said but instead of trimming you could use the replace() method on the string. As this ensures that any '=' will be replaced by ' ' instead of at the start

for dict in the_dicts: if '=' in dict['statement']: dict['statement'].replace('=',' ')

Upvotes: 1

Michael Bianconi
Michael Bianconi

Reputation: 5242

Iterate through the dictionary and check each statement. If it starts with '=', trim it off (or you can replace it with some string using string concatenation).

for my_dict in my_dicts:
    if my_dict['statement'].startswith('='):
        my_dict['statement'] = my_dict['statement'][1:]

Upvotes: 2

Related Questions