Python:how to use regex search in dict
Question:
how to do regex on dic key?
getting expected string or bytes-like object, got ‘dict’ with below code.
Thanks
with open('fbg3.csv','r') as file:
csvreader=csv.DictReader(file)
regex=r"^REPW+BGR30$"
for row in csvreader:
if re.match(regex,row):
print(row)
fbg3.csv
REPRESENTATIVE_BGR30,LEAD_AGR31,....
1,2,3
11,22,33
.............
expected output: REPRESENTATIVE_BGR30:1,11,..
Answers:
I hope it works for your problem.
Solution 1: (Using Pandas)
import pandas as pd
df = pd.read_csv('./regex_in_csv.csv')
d = {
'REPRESENTATIVE_BGR30': ''
}
d['REPRESENTATIVE_BGR30'] = ', '.join([str(i) for i in df.REPRESENTATIVE_BGR30])
d
Solution 2: (using DictReader)
import csv
import re
with open('./regex_in_csv.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
regex=r"^REPw+BGR30$"
d = {}
for row in reader:
for key, item in row.items():
if re.match(regex, key):
if 'REPRESENTATIVE_BGR30' in d:
d['REPRESENTATIVE_BGR30'] = d['REPRESENTATIVE_BGR30'] + ', ' + item
else:
d['REPRESENTATIVE_BGR30'] = item
d
how to do regex on dic key?
getting expected string or bytes-like object, got ‘dict’ with below code.
Thanks
with open('fbg3.csv','r') as file:
csvreader=csv.DictReader(file)
regex=r"^REPW+BGR30$"
for row in csvreader:
if re.match(regex,row):
print(row)
fbg3.csv
REPRESENTATIVE_BGR30,LEAD_AGR31,....
1,2,3
11,22,33
.............
expected output: REPRESENTATIVE_BGR30:1,11,..
I hope it works for your problem.
Solution 1: (Using Pandas)
import pandas as pd
df = pd.read_csv('./regex_in_csv.csv')
d = {
'REPRESENTATIVE_BGR30': ''
}
d['REPRESENTATIVE_BGR30'] = ', '.join([str(i) for i in df.REPRESENTATIVE_BGR30])
d
Solution 2: (using DictReader)
import csv
import re
with open('./regex_in_csv.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
regex=r"^REPw+BGR30$"
d = {}
for row in reader:
for key, item in row.items():
if re.match(regex, key):
if 'REPRESENTATIVE_BGR30' in d:
d['REPRESENTATIVE_BGR30'] = d['REPRESENTATIVE_BGR30'] + ', ' + item
else:
d['REPRESENTATIVE_BGR30'] = item
d