All Courses

HOW TO CREATE DICTIONARY COMPREHENSION:

Sulochana Kamshetty

3 years ago

DICTIONARY COMPREHENSION
Table of Content
  • What is DICTIONARY COMPREHENSION?
  • Create dictionary with different ways using different data types
  • Output
  • Second method creating simple dictionary
  • Output
  • Explanation
Let's understand
What is DICTIONARY COMPREHENSION?
Where and when it’s used in our python programming language?
In this article, we will also understand, about the concept as well as coding part in python with the help of some examples.
So Dictionaries are data types in Python which allows us to store data in key/value pair
Coding part with Example Dictionaries (or dict in Python) is a way of storing elements just like you would in a Python list.
Lets understand first about what is dictionaries how its created with coding in python
Create dictionary with different ways using different data types
 Our first and simple dictionary is creating an empty dictionary
>>> empty = {}

>>> empty

{}
Output:- Empty Dictionary: {}
Use of empty list: empty list is created for if u want to create any dictionary in between of any program it can be used in emergency case without disturbing the whole program
Second method creating simple dictionary:-
My_dict= {
 "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(my_dict)
Output:-
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Explanation:- 
Step 1:- Created variable called my_dict with a list of items into it with the different data types those are using numerical values and using characters into it after executing with the output using print function received the output in the form of a dictionary.
Let us understand how to create dictionary comprehension
Like List Comprehension, Python allows dictionary comprehensions. We can create dictionaries using simple expressions.
Lists to represent keys and values:-
keys = ['a','b','c','d','e'] 
values = [1,2,3,4,5]  
# but this line shows dictionary comprehension
here   
My_Dict = { k:v for (k,v) in zip(keys, values)}   
# We can use below too 
# my_Dict = dict(zip(keys, values))   
print (my_Dict) 
Output :
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
Explanation:-
Creating dictionary comprehension creating a new variable with the name with a list of keys and values into it and also using zip function in dictionary comprehension has concatenated two different datasets with one dictionary or set of values extracting the first value from the first variable and the first value of the second variable.
For more such blogs/courses on data science, machine learning, artificial intelligence and emerging new technologies do visit us at InsideAIML.
Thanks for reading…
Happy Learning…  

Submit Review