user1971598
user1971598

Reputation:

Making a dictionary where values are based off of a regex - Python

Say I have a dictionary x = {'123A......': None, '123AA.....': None, '123AB.....': None}

Assume I also have a list y = ['123AC.....', '123ABB....', '123ABC....']

what I want is the following result:

{'123A......': [123AC....], '123AA.....': ['123AC.....'], '123AB.....': ['123ABB....']}

I thought something like the following could work,

for item in x:
    x[item] = re.findall(r'123[A-Z\.]{7}', ''.join(y))

Or something like that. Help appreciated.

Upvotes: 0

Views: 73

Answers (1)

TehTris
TehTris

Reputation: 3217

you may want something like this

for item in xrange(len(x)):
      x[x.keys()[item]] = re.findall(r'123[A-Z\.]{7}', ''.join(y[item]))

this way both x and y are being incremented...

but im pretty sure this can be done even easier with zip

if you have:

x = ['123A......', '123AA......', '123AB......'] 
y = ['123AC.....', '123ABB....', '123ABC....']

dict(zip(x,y))

it will output

{'123AB......': '123ABC....', '123A......': '123AC.....', '123AA......': '123ABB....'}

which i believe would work for you and its waaaaaay easier, because it would preserve the order of the lists ( list item x[0] will be paired with y[0] ) and if you just incr the keys of the dict... weird order stuff happens..... play around with dict(zip(listA,listB)) and youll see what im talking about

Upvotes: 2

Related Questions