Page 311 - CTS - CSA TP - Volume 2
P. 311

COMPUTER SOFTWARE APPLICATION - CITS




           # Print the converted temperatures
           print(“Temperatures (Fahrenheit):”, temperatures_fahrenheit)
           Explanation:

           1  Temperatures_celsius = {‘city1’: 25, ‘city2’: 30, ‘city3’: 22, ‘city4’: 18}: Initializes a dictionary with city names as
              keys and temperatures in Celsius as values.
           2.  Temperatures_fahrenheit = {city: (temp * 9/5) + 32 for city, temp in temperatures_celsius.items()}:

           •  This is a dictionary comprehension.
           •  For city, temp in temperatures_celsius.items(): Iterates over each city and temperature in the original dictionary.
           •  {city: (temp * 9/5) + 32}: Creates a new key-value pair in the dictionary, where the key is the city, and the value
              is the temperature converted to Fahrenheit.

           3  Print(“Original Temperatures (Celsius):”, temperatures_celsius): Prints the original temperatures in Celsius.
           4  Print(“Temperatures (Fahrenheit):”, temperatures_fahrenheit): Prints the dictionary of temperatures converted
              to Fahrenheit.

           Output:









           Related Exercises :
           List Comprehensions:
           1  Create a list comprehension that generates the squares of numbers from 1 to 10.
           2  Generate a list of even numbers from 1 to 20 using list comprehension.
           3  Given a list of strings, create a new list containing the lengths of each string.

           Tuple Comprehensions:
           1  Generate a tuple comprehension that contains cubes of numbers from 1 to 5.
           2  Create a tuple of characters at odd indices from a given string.
           Set Comprehensions:

           1  Generate a set comprehension that contains unique squares of numbers from 1 to 10.
           2  Create a set of vowels present in a given string.
           Dictionary Comprehensions:
           1  Given two lists, create a dictionary where elements from the first list are keys, and elements from the second
              list are values.
           2  Count the frequency of each character in a string and create a dictionary using dictionary comprehension.
           3  Given a dictionary containing temperatures in Celsius, create a new dictionary with temperatures converted to
              Fahrenheit.















                                                           296

                              CITS : IT & ITES - Computer Software Application - Exercise 135
   306   307   308   309   310   311   312   313   314   315   316