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,..

Asked By: user2333234

||

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
Answered By: Muhammad Ali
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.