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

Time:02-07

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

CodePudding user response:

(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.

CodePudding user response:

yes, you need to iterate through the dictionary and check if the value is an int then square it and if it is not capitalize it

result = []
for key, value in dictionary.items()
    if type(value) is int:
        result.append(value**2)
    else:
        result.append(value.capitalize())
print(result)

this should print the desired output

  •  Tags:  
  • Related