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.
READ MORE »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 -
- Keys : Think about columns in tables. It must be unique (like column names cannot be duplicate)
- Values : It is similar to rows in tables. It can be duplicate.
Syntax of Dictionary
To extract keys, values and structure of dictionary, you can submit the following commands.
d = {'a': [1,2], 'b': [3,4], 'c': [5,6]}
Like R or SAS, you can create dataframe or dataset using pandas package in python.
d.keys() # 'a', 'b', 'c'
d.values() # [1, 2], [3, 4], [5, 6]
d.items()
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 runfor 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.
It creates dictionary
keys = ['a', 'b', 'c']
values = [1, 2, 3]
{i:j for (i,j) in zip(keys, values)}
{'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]
from Planet Python
via read more
No comments:
Post a Comment