I have a python dictionary consisting of key value pairs. What I want to do is delete items who’s keys are a certain format. In my case format of the keys I want to delete are: Letter, number, number. Example: A12, A56, A32
So in the below case I want to delete all the items that consist of an Axx (where the x’s are numbers).
{'A34': 83, 'B32': 70, 'A44': 66, A12: 47, 'B90': 71}
I know that the format can be targeted using regex. For example the following code will count the number of keys that have the Axx format (where x’s are numbers)
print(sum(1 for k in d.keys() if re.match('^A\\d{2}$', k)))
But how can I change this around so that it can delete the item of the dictionary whos key Is of the Axx format.
CodePudding user response:
You can use dictionary comprehension:
dct = {'A34': 83, 'B32': 70, 'A44': 66, 'A12': 47, 'B90': 71}
dct = {k:v for k,v in dct.items() if not re.fullmatch(r'A\d{2}', k) }
The if not re.fullmatch(r'A\d{2}', k)
condition filters out (removes) any items with key that fully matches A<two digits>
pattern (note that re.fullmatch
requires a full string match hence no need for anchors).
CodePudding user response:
for key in dictionary:
if condition(key):
del dictionary[key]
# Adapted to your code
temp = dictionary.copy()
for k in dictionary:
if re.fullmatch(r'A\d{2}', k):
del temp[k]
dictionary = temp
CodePudding user response:
You can delete the matches with pop
or del
. To avoid modifying the dictionary while iterating over it you can iterate over the dictionary keys
d = {'A34': 83, 'B32': 70, 'A44': 66, 'A12': 47, 'B90': 71}
for k in list(d.keys()):
if re.match('^A\\d{2}$', k):
d.pop(k) # del d[k]
print(d) # {'B32': 70, 'B90': 71}