In this article, we will discuss different ways to create dictionary objects in python.
What is a dictionary?
dictionary is an associative container that contains the items in key/value pairs. For example, we if want to track the words and their frequency count in an article like,
“Hello” occurs 7 times
“hi” occurs 10 times
“there” occurs 45 times
“at” occurs 23 times
“this” occurs 77 times
We can use the python dictionary to keep this data, where the key will the string word and value is the frequency count.
Now let’s see different ways to create a dictionary,
Creating Empty Dictionary
We can create an empty dictionary in 2 ways i.e.
''' Creating empty Dictionary ''' # Creating an empty dict using empty brackets wordFrequency = {} # Creating an empty dict using dict() wordFrequency = dict()
It will create an empty dictionary like this,
{}
Creating Dictionaries with literals
We can create a dictionary by passing key-value pairs literals i.e.
''' Creating Dictionaries with literals ''' wordFrequency = { "Hello" : 7, "hi" : 10, "there" : 45, "at" : 23, "this" : 77 }
It will create a dictionary like this,
{'this': 77, 'there': 45, 'hi': 10, 'at': 23, 'Hello': 7}
Creating Dictionaries by passing parameters in dict constructor
We can create a dictionary by passing key-value pairs in dictionary constructor i.e.
''' Creating Dictionaries by passing parametrs in dict constructor ''' wordFrequency = dict(Hello = 7, hi = 10, there = 45, at = 23, this = 77 )
It will create a dictionary like this,
{'there': 45, 'hi': 10, 'this': 77, 'at': 23, 'Hello': 7}
Creating Dictionaries by a list of tuples
Suppose we have a list of tuples i.e.
# List of tuples listofTuples = [("Hello" , 7), ("hi" , 10), ("there" , 45),("at" , 23),("this" , 77)]
We can create a dict out of this list of tuple easily by passing it in constructor i.e.
# Creating and initializing a dict by tuple wordFrequency = dict(listofTuples)
It will create a dictionary like this,
{'this': 77, 'there': 45, 'hi': 10, 'at': 23, 'Hello': 7}
Creating a Dictionary by a list of keys and initializing all with the same value
Suppose we have a list of string i.e.
listofStrings = ["Hello", "hi", "there", "at", "this"]
Now we want to create a dictionary where all the elements of the above list will be keys and their default value is 0.
We can do that using fromkeys() function of dict i.e.
# create and Initialize a dictionary by this list elements as keys and with same value 0 wordFrequency = dict.fromkeys(listofStrings,0 )
It will Iterate over the list of string and for each element, it will create a key-value pair with value as default value provided and store them in dict.
It will create a dictionary like this,
{'this': 0, 'there': 0, 'hi': 0, 'at': 0, 'Hello': 0}
Creating a Dictionary by two lists
Suppose we have two lists i.e.
List of strings,
# List of strings listofStrings = ["Hello", "hi", "there", "at", "this"]
List of integers,
# List of ints listofInts = [7, 10, 45, 23, 77]
Now we want to use elements in the list of string as keys and items in the list of ints as value while creating a dictionary.
To do that we are going to use zip() function that will Iterate over the two lists in parallel.
For each entry in the list, it will create a key-value pair and finally create a zipped object. Now, we can pass this zipped object to dict() to create a dictionary out of it i.e.
# Merge the two lists to create a dictionary wordFrequency = dict( zip(listofStrings,listofInts ))
# Merge the two lists to create a dictionary wordFrequency = dict( zip(listofStrings,listofInts ))
It will create a dictionary like this,
{'this': 77, 'there': 45, 'hi': 10, 'at': 23, 'Hello': 7}
Python Dictionary Tutorial - Series:
- What is a Dictionary in Python & why do we need it?
- Creating Dictionaries in Python
- Iterating over dictionaries
- Check if a key exists in dictionary
- Check if a value exists in dictionary
- Get all the keys in Dictionary
- Get all the Values in a Dictionary
- Remove a key from Dictionary
- Add key/value pairs in Dictionary
- Find keys by value in Dictionary
- Filter a dictionary by conditions
- Print dictionary line by line
- Convert a list to dictionary
- Sort a Dictionary by key
- Sort a dictionary by value in descending or ascending order
- Dictionary: Shallow vs Deep Copy
- Remove keys while Iterating
- Get all keys with maximum value
- Merge two or more dictionaries in python
Subscribe with us to join a list of 2000+ programmers and get latest tips & tutorials at your inbox through our weekly newsletter.
The complete example is as follows,
def main(): ''' Creating empty Dictionary ''' # Creating an empty dict using empty brackets wordFrequency = {} # Creating an empty dict using dict() wordFrequency = dict() print(wordFrequency) ''' Creating Dictionaries with literals ''' wordFrequency = { "Hello" : 7, "hi" : 10, "there" : 45, "at" : 23, "this" : 77 } print(wordFrequency) ''' Creating Dictionaries by passing parametrs in dict constructor ''' wordFrequency = dict(Hello = 7, hi = 10, there = 45, at = 23, this = 77 ) print(wordFrequency) ''' Creating Dictionaries by a list of tuples ''' # List of tuples listofTuples = [("Hello" , 7), ("hi" , 10), ("there" , 45),("at" , 23),("this" , 77)] # Creating and initializing a dict by tuple wordFrequency = dict(listofTuples) print(wordFrequency) ''' Creating Dictionary by a list of keys and initialzing all with same value ''' listofStrings = ["Hello", "hi", "there", "at", "this"] # create and Initialize a dictionary by this list elements as keys and with same value 0 wordFrequency = dict.fromkeys(listofStrings,0 ) print(wordFrequency) ''' Creating a Dictionary by a two lists ''' # List of strings listofStrings = ["Hello", "hi", "there", "at", "this"] # List of ints listofInts = [7, 10, 45, 23, 77] # Merge the two lists to create a dictionary wordFrequency = dict( zip(listofStrings,listofInts )) print(wordFrequency) if __name__ == "__main__": main()
Output:
{} {'hi': 10, 'there': 45, 'this': 77, 'at': 23, 'Hello': 7} {'there': 45, 'hi': 10, 'this': 77, 'at': 23, 'Hello': 7} {'hi': 10, 'there': 45, 'this': 77, 'at': 23, 'Hello': 7} {'hi': 0, 'there': 0, 'this': 0, 'at': 0, 'Hello': 0} {'hi': 10, 'there': 45, 'this': 77, 'at': 23, 'Hello': 7}
Pandas Tutorials -Learn Data Analysis with Python
-
Pandas Tutorial Part #1 - Introduction to Data Analysis with Python
-
Pandas Tutorial Part #2 - Basics of Pandas Series
-
Pandas Tutorial Part #3 - Get & Set Series values
-
Pandas Tutorial Part #4 - Attributes & methods of Pandas Series
-
Pandas Tutorial Part #5 - Add or Remove Pandas Series elements
-
Pandas Tutorial Part #6 - Introduction to DataFrame
-
Pandas Tutorial Part #7 - DataFrame.loc[] - Select Rows / Columns by Indexing
-
Pandas Tutorial Part #8 - DataFrame.iloc[] - Select Rows / Columns by Label Names
-
Pandas Tutorial Part #9 - Filter DataFrame Rows
-
Pandas Tutorial Part #10 - Add/Remove DataFrame Rows & Columns
-
Pandas Tutorial Part #11 - DataFrame attributes & methods
-
Pandas Tutorial Part #12 - Handling Missing Data or NaN values
-
Pandas Tutorial Part #13 - Iterate over Rows & Columns of DataFrame
-
Pandas Tutorial Part #14 - Sorting DataFrame by Rows or Columns
-
Pandas Tutorial Part #15 - Merging or Concatenating DataFrames
-
Pandas Tutorial Part #16 - DataFrame GroupBy explained with examples
Are you looking to make a career in Data Science with Python?
Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.
Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.
Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.