Thursday, July 4, 2019

ListenData: Python Dictionary Comprehension with Examples

In this tutorial, we will cover how dictionary comprehension works in Python. It includes various examples which would help you to learn the concept of dictionary comprehension and how it is used in real-world scenarios.
What is Dictionary?
Dictionary is a data structure in python which is used to store data such that values are connected to their related key. Roughly it works very similar to SQL tables or data stored in statistical softwares. It has two main components -
  1. Keys : Think about columns in tables. It must be unique (like column names cannot be duplicate)
  2. Values : It is similar to rows in tables. It can be duplicate.
It is defined in curly braces { }. Each key is followed by a colon (:) and then values.
Syntax of Dictionary

d = {'a': [1,2], 'b': [3,4], 'c': [5,6]}
To extract keys, values and structure of dictionary, you can submit the following commands.

d.keys() # 'a', 'b', 'c'
d.values() # [1, 2], [3, 4], [5, 6]
d.items()
Like R or SAS, you can create dataframe or dataset using pandas package in python.

import pandas as pd
pd.DataFrame(data=d)

a b c
0 1 3 5
1 2 4 6

What is Dictionary Comprehension?

Like List Comprehension, Dictionary Comprehension lets us to run for loop on dictionary with a single line of code.

Both list and dictionary comprehension are a part of functional programming which aims to make coding more readable and create list and dictionary in a crisp way without explicitly using for loop.

The difference between list and dictionary comprehension is that list comprehension creates list. Whereas dictionary comprehension creates dictionary. Syntax is also slightly different (refer the succeeding section). List is defined with square bracket [ ] whereas dictionary is created with { }

Syntax of Dictionary Comprehension

{key: value for (key, value) in iterable}
Iterable is any python object in which you can loop over. For example, list, tuple or string.

keys = ['a', 'b', 'c']
values = [1, 2, 3]
{i:j for (i,j) in zip(keys, values)}
It creates dictionary {'a': 1, 'b': 2, 'c': 3}. It can also be written without dictionary comprehension like dict(zip(keys, values)).

You can also execute dictionary comprehension with just defining only one variable i. In the example below, we are taking square of i for assigning values in dictionary.

range(5) returns 0 through 4 as indexing in python starts from 0 and excluding end point. If you want to know how dictionary comprehension is different from For Loop, refer the table below.

Dictionary Comprehension

d = {i:i**2 for i in range(5)}
For Loop

d = {}
for i in range(5):
d[i]=i**2
print(d)

Output
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

d.keys() returns [0, 1, 2, 3, 4]
d.values() returns [0, 1, 4, 9, 16]
READ MORE »

from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...