0

I am using Python 2.7 and trying to split a dict containing nested values into multiple dicts containing specific values. My initial dict is as follows:

d = {'V1': [['10', 'AND', '2'], 'OR', ['5', 'AND', '1']], 'V2': ['4', 'OR', '1'], 'V3': ['4', 'AND', '4'], 'V4': ['100']} 

I am trying to get:

d1 = {'V1': [['10', 'AND', '2'], 'OR', ['5', 'AND', '1']]} #nested key:values containing OR, AND operators

d2 = {'V2': ['4', 'OR', '1']} #key:values containing only OR operator

d3 = {'V3': ['4', 'AND', '4']} #key:values containing only AND operator

d4 = {'V4': ['100']} #key:values containing no linking OR, AND operators

I have tried list comprehension but get stuck with separating the nested values containing both AND, OR operators. For example:

OR_dict = {k:v for k, v in d.items() if 'OR' in v}
# {'V1': [['10', 'AND', '2'], 'OR', ['5', 'AND', '1']], 'V2': ['4', 'OR', '1']}

For separating key:values containing only AND operator I have tried the following and have had some success:

AND_dict = {k:v for k, v in d.items() for i in v if i=='AND'}
# {'V3': [['4', 'AND', '4']}

I have looked at related questions: python split dict by value and python split dict by key but haven't been able to solve my problem. Any help would be appreciated.

David H
  • 23
  • 3
  • Huh... it seems like you want to split the top level keys into separate dicts... am I wrong? – cs95 Dec 15 '17 at 18:01
  • Anyway, what you're doing isn't good practice... strive to keep things in a single dictionary. – cs95 Dec 15 '17 at 18:01
  • The original dict is generated by parsing a file that contains multiple occurrences of keys:nested values. I'd like to bin them into separate dicts as I need to process values based on the presence of OR, AND operators. – David H Dec 15 '17 at 18:29

0 Answers0