Transform value of all keys in dict with value matching condition

Question:

Given a dict like below

{'a': [{'id': 0, 'res': [0, 1]}, {'id': 1, 'res': [8, 9]}], 'b': [{'id': 26, 'f': ('f3', {'nrP': 1})}, {'if': 0, 'f': ('f1', {'init': 6, 'nrS': 14})}], 'c': ('setup', {}), 'd': ('setup', {'max': 'one', 'sim': 'true'}), 'e': [{'id': 8, 'period': ('sl160', 8), 'res': 23}], 'f': [2, 3], 'g': {'f0': 0, 'p0': [{'id': 1, 'Value': -1}], 'ref': [{'id': 0, 'rs': ('abc', 0)}]}}

Need to have all key’s (including the nested ones) whose value is 1) for which the value is a tuple & 2) has exactly 2 elements in tuple and 3) both the elements are either strings or numbers (not dict/list or other data structure) converted to a string tuple[0] + ":" + tuple[1].

Examples keys that would match the data above would be – 'period': ('sl160', 8) & 'rs': ('abc', 0)

For the above example the expected result would be as below.

{'a': [{'id': 0, 'res': [0, 1]}, {'id': 1, 'res': [8, 9]}], 'b': [{'id': 26, 'f': ('f3', {'nrP': 1})}, {'if': 0, 'f': ('f1', {'init': 6, 'nrS': 14})}], 'c': ('setup', {}), 'd': ('setup', {'max': 'one', 'sim': 'true'}), 'e': [{'id': 8, 'period': 'sl160 : 8', 'res': 23}], 'f': [2, 3], 'g': {'f0': 0, 'p0': [{'id': 1, 'Value': -1}], 'ref': [{'id': 0, 'rs': 'abc : 0'} ]}}

The conversion of the tuple to the string is fairly ok. I need to identify nested keys matching the condition above and do the transformation in place.

Asked By: user3206440

||

Answers:

The below works

def convertTwoElmStrTupleToStr(dictIe):
    if isinstance(dictIe, dict):
        # base case
        for k, v in dictIe.items():
            if isinstance(v, tuple) and len(v) == 2 and (isinstance(v[0], str) or isinstance(v[0], int)) and (isinstance(v[1], str) or isinstance(v[1], int)):
                dictIe[k] = f'{v[0]} : {v[1]}'
            elif isinstance(v, list):
                for item in v:
                    if isinstance(item, dict):
                       # call base case on each dict
                        convertTwoElmStrTupleToStr(item)
            elif isinstance(v, dict):
                     # call base case on each dict
                    convertTwoElmStrTupleToStr(v)

    return dictIe

Output

>>> convertTwoElmStrTupleToStr(a)
{'a': [{'id': 0, 'res': [0, 1]}, {'id': 1, 'res': [8, 9]}], 'b': [{'id': 26, 'f': ('f3', {'nrP': 1})}, {'if': 0, 'f': ('f1', {'init': 6, 'nrS': 14})}], 'c': ('setup', {}), 'd': ('setup', {'max': 'one', 'sim': 'true'}), 'e': [{'id': 8, 'period': 'sl160 : 8', 'res': 23}], 'f': [2, 3], 'g': {'f0': 0, 'p0': [{'id': 1, 'Value': -1}], 'ref': [{'id': 0, 'rs': 'abc : 0'}]}}
Answered By: user3206440
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.