How to split values of a Python dictionary

Question:

I have a dictionary like this:

data = {
key1: [ <A><B> ]
key2: [ <C><D> ]
key3: [ <A><F> ]
...
}

Goal to achieve:

I want to have instead something like this:

new_dict = {
key1: [ <A>, <B> ]
key2: [ <C>, <D> ]
key3: [ <A>, <F> ]
...
}

And then extract only the keys with "< A>" as first value and save them in a list. Something like this:

A_as_first_value = [key1, key3]

After having a list with all these keys, I also want a list with all the second values. Something like this:

second_values_ = [<B>, <F>]
Asked By: dom

||

Answers:

User regular expression to findall the substrings matching the pattern <w> where w basically means a word character, then filter out the keys for the resulting list of values.

import re
pattern=re.compile('<w>')
out={k:pattern.findall(v[0]) for k,v in data.items()} # data is your dict
# out
# {'key1': ['<A>', '<B>'], 'key2': ['<C>', '<D>'], 'key3': ['<A>', '<F>']}
A_as_first_value = [k for k in out if out[k][0]=='<A>']
# A_as_first_value
# ['key1', 'key3']

Then from the resulting list of keys above, get the values at second index for values in the given keys in the resulting dictionary:

second_values=[out[k][1] for k in A_as_first_value]
# second_values
# ['<B>', '<F>']
Answered By: ThePyGuy