Search code examples
listdictionarylist-comprehension

How to get specific values from a dictionary using list comprehension and modify them?


Can someone help and kindly advise how Can I get specific values from this dictionary (Using list comprehension) and

  1. square the values only,
  2. change every string value, so it starts with upper case?
items_list = {'a': 3, 'b':6, 'c': 'short', 'h': 'example', 'p': 77}

So, the output needs to be:

9, 36, 5929
Short, Example

Solution

  • (Python):

    items_list = {'a': 3, 'b': 6, 'c': 'short', 'h': 'example', 'p': 77}
    
    lst = [v ** 2 if isinstance(v, (int, float)) else v.capitalize() for v in
           items_list.values()]
    
    print(lst)
    

    output:

    [9, 36, 'Short', 'Example', 5929]
    

    The exact output that you showed can not be produced using single list comprehension, because the iteration is in order.