Search code examples
pythondictionary-comprehension

tuple with dict to list with element modification


Given tuple like below,

tpl = ('abc', {'a': 1, 'b': 2})

need to create a list out of this preferably through comprehension if possible.

Expected output

['abc', 'a: 1', 'b: 2']

Tuple can be converted to a list by calling list(tpl)

The part where the dict key:val is converted to key + " : " + val can be done by something like below

[k + " : " + v for k, v in dict.items()]

I think the part of selectively calling the above manipulation be done by checking the type (only for dict) - need some help to get to the complete solution.

Also as a separate problem, is there a way to do this inplace ?


Solution

  • A solution using list-comprehension.

    tpl = ('abc', {'a': 1, 'b': 2})
    answer = [
      x for dict_or_str in tpl for x in 
      ( 
        [f"{k}: {v}" for k, v in dict_or_str.items()] 
        if isinstance(dict_or_str, dict)
        else [dict_or_str]
      )
    ]
    print(answer)
    

    Output

    ['abc', 'a: 1', 'b: 2']