Home > Mobile >  String matching and storing within a dictionary
String matching and storing within a dictionary

Time:10-09

I'm using pattern matching to collect the postcodes belonging to a street address and storing these addresses as values within a dictionary, here is what I have tried:

test = pd.DataFrame(['SR2', 'SA1', 'M16', 'KY6', 'SR6'], columns=(['postcode']))

street = pd.DataFrame(['UnnamedRoad,LlandeiloSA196UA,UK', '8NewRd,LlandeiloSA196DB,UK','1RomanRd,Banwen,NeathSA109LH,UK', 'UnnamedRoad,LlangadogSA199UN,UK', '48ColeAve,ChadwellStMary,GraysRM164JQ,UK', '37WellingtonRd,NorthWealdBassett,EppingCM166JY,UK'], columns=(['address']))

dictframe = {}
for i in test['postcode']:
    dictframe[i] = list()
    for k in range(0, len(test), 1):    
        dictframe[i].append(list(filter(lambda x: test['postcode'][k] in x, street['address'])))

However this prints all the outputs in each key, but I wanted only for where values appear to be within the key otherwise keep the list empty if nothing match. Here's the output I get:

{'SR2': [[],
  ['UnnamedRoad,LlandeiloSA196UA,UK',
   '8NewRd,LlandeiloSA196DB,UK',
   '1RomanRd,Banwen,NeathSA109LH,UK',
   'UnnamedRoad,LlangadogSA199UN,UK'],
  ['48ColeAve,ChadwellStMary,GraysRM164JQ,UK',
   '37WellingtonRd,NorthWealdBassett,EppingCM166JY,UK'],
  [],
  []],
..
..
..

Expected output:

{'SR2': [],
'SA1': ['UnnamedRoad,LlandeiloSA196UA,UK',
   '8NewRd,LlandeiloSA196DB,UK',
   '1RomanRd,Banwen,NeathSA109LH,UK',
   'UnnamedRoad,LlangadogSA199UN,UK']
...
...
}

CodePudding user response:

corrected code - inner for loop is not required & in the string matching the index of test['postcode'] needs to be used, refer Python enumerate

import pandas as pd
test = pd.DataFrame(['SR2', 'SA1', 'M16', 'KY6', 'SR6'], columns=(['postcode']))

street = pd.DataFrame(['UnnamedRoad,LlandeiloSA196UA,UK', '8NewRd,LlandeiloSA196DB,UK','1RomanRd,Banwen,NeathSA109LH,UK', 'UnnamedRoad,LlangadogSA199UN,UK', '48ColeAve,ChadwellStMary,GraysRM164JQ,UK', '37WellingtonRd,NorthWealdBassett,EppingCM166JY,UK'], columns=(['address']))

dictframe = {}
for index, i in enumerate(test['postcode']):
    dictframe[i] = list()
    #for k in range(0, len(street), 1):    
    dictframe[i].append(list(filter(lambda x: test['postcode'][index] in x, street['address'])))

Output-

{'KY6': [[]],
 'M16': [['48ColeAve,ChadwellStMary,GraysRM164JQ,UK',
   '37WellingtonRd,NorthWealdBassett,EppingCM166JY,UK']],
 'SA1': [['UnnamedRoad,LlandeiloSA196UA,UK',
   '8NewRd,LlandeiloSA196DB,UK',
   '1RomanRd,Banwen,NeathSA109LH,UK',
   'UnnamedRoad,LlangadogSA199UN,UK']],
 'SR2': [[]],
 'SR6': [[]]}
  • Related