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)
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'}
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'}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.