Dictionary and List

Question

What are Dict and List comprehensions?

in progress 0
Pragya Rani 55 years 1 Answer 830 views Contributor 0

Answer ( 1 )

  1. Dict and List comprehensions in python are used to perform tasks with
    much lesser code than you would have required to do in most of the
    other programming languages.

    For example i have a list and i need to perform certain operation on
    all the elements of the list.
    The traditional would be something lie this

    squares = []
    for num in range(10):
    squares.append(num**2)
    squares

    OUTPUT :
    [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

    With list comprehension we can do it in one line of code
    The basic syntax for list comprehensions is this: [EXPRESSION FOR ELEMENT IN SEQUENCE].
    code:
    squares = [x**2 for x in range(10)]

    OUTPUT :
    [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

    The same style can be extended to Dictionaries

    A dictionary comprehension takes the form {key: value for (key, value) in iterable}
    # List of tuples
    openers = [(‘Shikhar’, ‘Rohit’), (‘Roy’, ‘Bairstow’), (‘Warner’, ‘Finch’)]

    #To create a dictionary
    openers_dict = {k: v for k, v in openers}

    openers_dict
    OUTPUT:
    {‘Shikhar’:’Rohit’,’Roy’:’Bairstow’,’Warner’:’Finch’}

Leave an answer

Browse
Browse