Home > Enterprise >  Create a class and use dictionary comprehension to print square and cube of elements of a python lis
Create a class and use dictionary comprehension to print square and cube of elements of a python lis

Time:10-28

I am fairly new to python and trying to figure out as to how to take a list an input in a python class and find out the cube of the elements, whether number is even or odd and finally print the square of the elements in the list. I have been trying but not able to find out the solution. Could someone kindly help me.

Here is the sample input

list1 = [0, 1, 2, 3, 4, 5]

Expected output would be something like below

{
  0: {'cube': 0, 'even' : True, 'square' : 0}
  1: {'cube': 1, 'even' : False, 'square' : 1}
  2: {'cube': 8, 'even' : True, 'square' : 4}
  3: {'cube': 27, 'even' : False, 'square' : 9}
  4: {'cube': 64, 'even' : True, 'square' : 16}
  5: {'cube': 125, 'even' : False, 'square' : 25}
}

CodePudding user response:

Just do some dictionary comprehension

list1 = [0, 1, 2, 3, 4, 5]
new_dict = {x: {'cube': x**3, 'even': x%2==0, 'square': x**2} for x in list1}

{0: {'cube': 0, 'even': True, 'square': 0},
 1: {'cube': 1, 'even': False, 'square': 1},
 2: {'cube': 8, 'even': True, 'square': 4},
 3: {'cube': 27, 'even': False, 'square': 9},
 4: {'cube': 64, 'even': True, 'square': 16},
 5: {'cube': 125, 'even': False, 'square': 25}}

CodePudding user response:

Using loop:

import math

list1 = [0, 1, 2, 3, 4, 5]
data = []

for x in list1:
  data[x] = 
    {
      'cube': x**3,
      'even': x%2==0,
      'square': math.sqrt(x)
    }

Using list comprehension:

import math

list1 = [0, 1, 2, 3, 4, 5]

data = {x: {'cube': x**3, 'even': x%2==0, 'square': math.sqrt(x)} for x in list1}

  • Related