I have the following Python dict:
d = {'A-x': 1, 'A-y': 2,
'B-x': 3,
'C-x': 4, 'C-y': 5,
'D-x': 6, 'D-y': 7,
'E-x': 8}
Where the keys here represent a "Level-SubLevel" pattern.
There is no B-y or E-y key and they can therefor be considered "missing".
I'm trying to detect these "missing" key Levels, so my expected output would be the list:
['B', 'E']
So far I have the following working solution...
import numpy as np
from itertools import product
a = np.array([k.split('-') for k in d])
all_keys = ['-'.join(x) for x in list(product(set(a[:, 0]), set(a[:, 1])))]
missing_keys = [x.split('-')[0] for x in all_keys - d.keys()]
... but I feel there must be a better/cleaner solution - ideally using the standard python library.
I should clarify also, that in this particular case, the "SubLevel" portion of the key can only be 1 of 2 possible values. So only "x" or "y". Also "...-x" will always exist, it's only possible that "...-y" may be missing.
Any suggestions would be much appreciated.
After clarifying in your question, that only '-y' keys might be missing, you can try this:
d = {'A-x': 1, 'A-y': 2,
'B-x': 3,
'C-x': 4, 'C-y': 5,
'D-x': 6, 'D-y': 7,
'E-x': 8}
out = [k for k in set(k.split('-')[0] for k in d) if not k+'-y' in d]
print(out)
Prints:
['B', 'E']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With