Reputation: 45
How could I parse the dictionary
below, so that it's values
only contain ticket numbers?
Current Dictionary:
{'8.8.8.8': 'Open Menu 10A-003272 10A-003328 10A-003652', '8.8.8.9': '10A-003069 10/21/2016', '8.8.8.10': 'Open Menu 10A-003145 10/21/2016'}
Objective Dictionary:
{'8.8.8.8': '10A-003272 10A-003328 10A-003652', '8.8.8.9': '10A-003069', '8.8.8.10': '10A-003145'}
Code used to make dictionary:
with open(esccbList, 'r') as f:
d = {}
for line in f:
d[line.strip()] = next(f, '').strip()
Regex to find ticket numbers:
n = re.search(r'10A-\d{6}',item, re.M|re.I)
Upvotes: 0
Views: 109
Reputation: 37691
I have updated my answer to print the dictionary in desired format.
import re
pattern = re.compile(r'10A-\d{6}')
info = {'8.8.8.8': 'Open Menu 10A-003272 10A-003328 10A-003652',
'8.8.8.9': '10A-003069 10/21/2016',
'8.8.8.10': 'Open Menu 10A-003145 10/21/2016'}
output = {}
for key, value in info.items():
tokens = value.split()
val = ''
for token in tokens:
if pattern.match(token):
val = val + token + ' '
val = val.strip()
output[key] = val;
print(output)
It prints:
{'8.8.8.8': '10A-003272 10A-003328 10A-003652',
'8.8.8.9': '10A-003069',
'8.8.8.10': '10A-003145'}
Upvotes: 1
Reputation: 3895
d = { k, clean_ticket(v) for k,v in original_dict.items() if is_ticket(v) }
Looks like is_ticket should be something like
def is_ticket(v):
return "Open Menu" in v
Make a function clean_ticket(v) that strips off the Open Menu
def clean_ticket(v):
return v.split("Open Menu")[1].strip()
Something like that.
Upvotes: 0
Reputation: 5228
I assume you have some function
def is_ticket_number(item):
""" returns True only if item is a ticket number """
return re.search(r'10A-\d{6}',item, re.M|re.I)
Then all you need to do is
d = {k: v for k, v in d.items() if is_ticket_number(v)}
Upvotes: -2
Reputation: 48067
Assuming that your ticket number substring will only contain hyphen -
, you may use a dict comprhension to achieve this like:
my_dict = {'8.8.8.8': 'Open Menu 10A-003272 10A-003328 10A-003652', '8.8.8.9': '10A-003069 10/21/2016', '8.8.8.10': 'Open Menu 10A-003145 10/21/2016'}
new = {k: ' '.join(i for i in v.split() if '-' in i) for k, v in my_dict.items()}
Final value hold by new
dict will be:
{'8.8.8.9': '10A-003069',
'8.8.8.10': '10A-003145',
'8.8.8.8': '10A-003272 10A-003328 10A-003652'}
Upvotes: 2