HAH
HAH

Reputation: 211

How do I remove [ ] and ' ' from my dictionary values so that I can print it properly in a csv file

I have a dictionary as an output. The values are messy. They are in form strings/list. I need to remove the square brackets and quotes from them so that I can print them properly in a CSV file. How can I achieve this?

This is the dictionary:

{'table': [['abc']], 'from': [['abc']], 'where_expr': ['c', '=', 'book']}

I want this to become something like this: {'table': abc, 'from': abc, 'where_expr': c, =,book} and my csv file as

table| from| where_expr

abc | abc |c = book

(I'm just showing different cols by using |)

dict1=delr.asDict()
with open('delf.csv', 'w') as f:  x
    w = csv.DictWriter(f, dict1.keys())
    w.writeheader()
    w.writerow(dict1)

Upvotes: 0

Views: 74

Answers (2)

U13-Forward
U13-Forward

Reputation: 71610

Then why not:

print({k: (', '.join(v[0]) if isinstance(v[0], list) else ', '.join(v)) for k,v in d.items()})

Output:

{'table': 'abc', 'from': 'abc', 'where_expr': 'c, =, book'}

Upvotes: 1

Mykola Zotko
Mykola Zotko

Reputation: 17882

You can use the following dictcomp:

{k: str(v).strip("[]").replace("'", "") for k, v in dct.items()}
# {'table': 'abc', 'from': 'abc', 'where_expr': 'c, =, book'}

Upvotes: 2

Related Questions