How to create dictionary in Python with example?

A Dictionary in Python is a type of data structure.It consists of a collection of key-value pairs. Each key in the dictionary is unique. Each unique key in the dictionary is associated to its value. Thus, Dictionary holds key : value pairs.

We will be discussing how to create a dictionary in Python.

Create a Dictionary

A dictionary in Python can be created by placing various key: value pairs inside curly braces .The key:value pairs are separated from each other using commas(,). The values in the dictionary can be of any datatype and can be duplicated. However, the keys in the dictionary cannot be repeated and must be immutable.

Dictionary keys are case-sensitive.This means two keys with same names but different cases will be treated distinctly.

Example

 Live Demo

dict1={1:"Tutorials",2:"Point",3:1116}
print("Dictionary 1",dict1)
dict2={1:"TutorialsPoint","TP":"DictionaryTutorial"}
print("Dictionary 2",dict2)

Output

Dictionary 1 {1: 'Tutorials', 2: 'Point', 3: 1116}
Dictionary 2 {1: 'TutorialsPoint', 'TP': 'DictionaryTutorial'}

As clear from the above example, the keys and values can have any datatype in a dictionary. But all the keys must be unique.

What if two keys in dictionary are given same name?

Let’s observe with the help of an example.

Example

 Live Demo

dict1={1:"Tutorials",1:"Point",3:1116}
print("Dictionary 1",dict1)

Output

Dictionary 1 {1: 'Point', 3: 1116}

The above example shows that if two keys in a dictionary are given same name, the previous key value is just overwritten.Here the “Tutorials” in key “1” is overwritten with “Point”.

We can have both these values or even more in a single key by assigning lists to keys.

Using “dict()” method

We can create dictionary in Python using the dict() method. Inside the dict() method, we will define the key : value pairs of the dictionary.

Example

 Live Demo

dict1=dict({1:"Tutorials",1:"Point",3:1116})
print("Dictionary 1",dict1)
dict2=dict([(1,"Tutorials"),(2,"Point")])
print("Dictionary 2",dict2)

The dict2 is a dictionary created using dict() method with each item as a Pair.

Output

Dictionary 1 {1: 'Point', 3: 1116}
Dictionary 2 {1: 'Tutorials', 2: 'Point'}

Creating Empty Dictionary

An empty dictionary can be created by simply placing two curly braces {}.

Example

 Live Demo

dict1={}
print("Dictionary 1",dict1)

Output

Dictionary 1 {}

Creating Nested Dictionary

Nested Dictionary as the name suggests means a dictionary inside a dictionary. In nested dictionary, a key can contain another dictionary.

Want to step up your Python game? Learn how to create dictionaries in Python from many different sources, including reading from JSON files and combining two dictionaries.

So, you've already figured out how to use dictionaries in Python. You know all about how dictionaries are mutable data structures that hold key-value pairs. You understand you must provide a key to the dictionary to retrieve a value. But you may not have realized dictionaries in Python come in all shapes and sizes and from all kinds of sources.

Just think about how many real-life objects can be modeled using key-value pairs: students and their grades, people and their occupations, products and their prices, just to name a few. Dictionaries are central to data processing in Python, and you run into them when loading data from files or retrieving data from the web.

Since Python dictionaries are so ubiquitous, it is no surprise you can build them from many different sources. In this article, we explore 5 ways to create dictionaries in Python. Let’s get started!

1. Python Dictionary From the Dictionary Literal {}

Not surprisingly, this is the most common method for creating dictionaries in Python. All you have to do is declare your key-value pairs directly into the code and remember to use the proper formatting:

  • Use
    grades = {
        'John': 7.5,
        'Mary': 8.9,
        'James': 9.0,
        # add more lines here …
    }
    
    0 to open the dictionary.
  • Use
    grades = {
        'John': 7.5,
        'Mary': 8.9,
        'James': 9.0,
        # add more lines here …
    }
    
    1 to define key-value pairs.
  • Use
    grades = {
        'John': 7.5,
        'Mary': 8.9,
        'James': 9.0,
        # add more lines here …
    }
    
    2 to separate key-value pairs from each other.
  • Use
    grades = {
        'John': 7.5,
        'Mary': 8.9,
        'James': 9.0,
        # add more lines here …
    }
    
    3 to close the dictionary.

Simple, but effective! Here’s a basic example of how this looks:

grades = {'John': 7.5, 'Mary': 8.9, 'James': 9.0}

Dictionaries ignore spaces and line breaks inside them. We can take advantage of this and write just one key-value pair per line. It improves readability, especially when our dictionaries grow a little too big to fit comfortably in a single line:

grades = {
    'John': 7.5,
    'Mary': 8.9,
    'James': 9.0,
    # add more lines here …
}

2. Python Dictionary From the dict() Constructor

Dictionaries can also be built from the Python

grades = {
    'John': 7.5,
    'Mary': 8.9,
    'James': 9.0,
    # add more lines here …
}
4 constructor.
grades = {
    'John': 7.5,
    'Mary': 8.9,
    'James': 9.0,
    # add more lines here …
}
4 is a built-in function in Python, so it is always available to use without the need to import anything.

You can use the Python

grades = {
    'John': 7.5,
    'Mary': 8.9,
    'James': 9.0,
    # add more lines here …
}
4 constructor in two ways. The first is to provide the key-value pairs through keyword arguments:

prices = dict(apple=2.5, orange=3.0, peach=4.4)
print(prices)

# output: {'apple': 2.5, 'orange': 3.0, 'peach': 4.4}

It’s fair to say the first method is easier to read and understand at a glance. However, keyword arguments are always interpreted as strings, and using keyword arguments may not be an option if you need a dictionary in which the keys are not strings. Take a look at this example to see what I mean:

# this works
values = [(1, 'one'), (2, 'two')]
prices = dict(values)

# SyntaxError - a number is not a valid keyword argument!
prices = dict(1='one', 2='two')

By the way, if you need a reminder, check out this great article on tuples and other sequences in Python.

3. Python Dictionary From a JSON File

JSON stands for JavaScript Object Notation, and it is an extremely common file format for storing and transmitting data on the web. Here’s an example JSON file, called

grades = {
    'John': 7.5,
    'Mary': 8.9,
    'James': 9.0,
    # add more lines here …
}
7:

{
    "name": "Mark",
    "age": 32,
    "likes_dancing": true
}

Notice anything? Yep! JSON files are pretty much identical to dictionaries in Python. So, it is no surprise you can load JSON data into Python very easily. We simply need to:

  • Import the
    grades = {
        'John': 7.5,
        'Mary': 8.9,
        'James': 9.0,
        # add more lines here …
    }
    
    8 module (don’t worry about installing anything; this module is part of Python’s base installation).
  • Open the
    grades = {
        'John': 7.5,
        'Mary': 8.9,
        'James': 9.0,
        # add more lines here …
    }
    
    7 file (take a look at this course if you don’t know what “opening a file” means in Python).
  • Pass the open file handle to the
    prices = dict(apple=2.5, orange=3.0, peach=4.4)
    print(prices)
    
    # output: {'apple': 2.5, 'orange': 3.0, 'peach': 4.4}
    
    0 function.

We take these steps in the code below:

import json

with open('person.json', 'r') as json_file:
    person = json.load(json_file)
print(person)

# output: {'name': 'Mark', 'age': 32, 'likes_dancing': True}

Note that you can also go the other way around and write a Python

grades = {
    'John': 7.5,
    'Mary': 8.9,
    'James': 9.0,
    # add more lines here …
}
4 into a JSON file. This process is called serialization. See this article for more information about serialization.

4. Python Dictionary From Two Dictionaries Using the Dictionary Union Operator

If you’re using Python version 3.9 or greater, there’s yet another way to create a dictionary in Python: the dictionary union operator (

prices = dict(apple=2.5, orange=3.0, peach=4.4)
print(prices)

# output: {'apple': 2.5, 'orange': 3.0, 'peach': 4.4}
2), introduced in Python 3.9. It merges the key-value pairs of two or more dictionaries into a single one. In that sense, it is similar to the set union operator (read this article if you don’t know what set operators are).

Here’s an example of the dictionary union operator in action:

jobs_1 = {
	'John': 'Engineer',
	'James': 'Physician',
}

jobs_2 = {
	'Jack': 'Journalist',
	'Jill': 'Lawyer',
}

jobs = jobs_1 | jobs_2
print(jobs)

# output: {'John': 'Engineer', 'James': 'Physician', 'Jack': 'Journalist', 'Jill': 'Lawyer'}

It’s important to note that, if there are duplicate keys in the source dictionaries, the resulting dictionary gets the value from the right-most source dictionary. This is a consequence of Python not allowing duplicate keys in a dictionary. Take a look at what happens here:

d1 = {
	'A': 1,
	'B': 2,
}

d2 = {
	'B': 100,
	'C': 3,
}

result = d1 | d2
print(result)

# output: {'A': 1, 'B': 100, 'C': 3}

As you can see,

prices = dict(apple=2.5, orange=3.0, peach=4.4)
print(prices)

# output: {'apple': 2.5, 'orange': 3.0, 'peach': 4.4}
3 appears in both
prices = dict(apple=2.5, orange=3.0, peach=4.4)
print(prices)

# output: {'apple': 2.5, 'orange': 3.0, 'peach': 4.4}
4 and
prices = dict(apple=2.5, orange=3.0, peach=4.4)
print(prices)

# output: {'apple': 2.5, 'orange': 3.0, 'peach': 4.4}
5. The value in the
prices = dict(apple=2.5, orange=3.0, peach=4.4)
print(prices)

# output: {'apple': 2.5, 'orange': 3.0, 'peach': 4.4}
6 dictionary comes from
prices = dict(apple=2.5, orange=3.0, peach=4.4)
print(prices)

# output: {'apple': 2.5, 'orange': 3.0, 'peach': 4.4}
5, the right-most source dictionary in the expression
prices = dict(apple=2.5, orange=3.0, peach=4.4)
print(prices)

# output: {'apple': 2.5, 'orange': 3.0, 'peach': 4.4}
8. The key-value pair
prices = dict(apple=2.5, orange=3.0, peach=4.4)
print(prices)

# output: {'apple': 2.5, 'orange': 3.0, 'peach': 4.4}
9 from
prices = dict(apple=2.5, orange=3.0, peach=4.4)
print(prices)

# output: {'apple': 2.5, 'orange': 3.0, 'peach': 4.4}
4 is lost. Keep this in mind when using the dictionary union operator!

5. Python Dictionary From a Dict Comprehension

Have you heard of list comprehensions? Once you get the hang of them, they are a great way to create new lists from already existing ones, either by filtering the elements or modifying them.

But what does it have to do with building dictionaries in Python? Well, a similar syntax is used for constructing dictionaries, in what we call a dict comprehension. In the example below, we take a list of strings and build a dictionary from them. Each key is the string itself, and the corresponding value is its length. Take a look:

animals = ['cat', 'lion', 'monkey']
animal_dict = {animal: len(animal) for animal in animals}
print(animal_dict)

# output: {'cat': 3, 'lion': 4, 'monkey': 6}

See how it works? For each

# this works
values = [(1, 'one'), (2, 'two')]
prices = dict(values)

# SyntaxError - a number is not a valid keyword argument!
prices = dict(1='one', 2='two')
1 in the list
# this works
values = [(1, 'one'), (2, 'two')]
prices = dict(values)

# SyntaxError - a number is not a valid keyword argument!
prices = dict(1='one', 2='two')
2, we build a key-value pair of the
# this works
values = [(1, 'one'), (2, 'two')]
prices = dict(values)

# SyntaxError - a number is not a valid keyword argument!
prices = dict(1='one', 2='two')
1 itself and its length (
# this works
values = [(1, 'one'), (2, 'two')]
prices = dict(values)

# SyntaxError - a number is not a valid keyword argument!
prices = dict(1='one', 2='two')
4).

Here’s a more intricate example. We use a dict comprehension to filter the values from a preexisting dictionary. See if you can figure out what the code below does:

ages = {
    'Bill': 23,
    'Steve': 34,
    'Maria': 21,
}
filtered_ages = {name: age for name, age in ages.items() if age < 30}
print(filtered_ages)

# output: {'Bill': 23, 'Maria': 21}

Do you see what happens? We use

# this works
values = [(1, 'one'), (2, 'two')]
prices = dict(values)

# SyntaxError - a number is not a valid keyword argument!
prices = dict(1='one', 2='two')
5 to get each key-value pair from the original dictionary and build
# this works
values = [(1, 'one'), (2, 'two')]
prices = dict(values)

# SyntaxError - a number is not a valid keyword argument!
prices = dict(1='one', 2='two')
6 based on that. But we add the
# this works
values = [(1, 'one'), (2, 'two')]
prices = dict(values)

# SyntaxError - a number is not a valid keyword argument!
prices = dict(1='one', 2='two')
7 bit at the end. So, during its construction,
# this works
values = [(1, 'one'), (2, 'two')]
prices = dict(values)

# SyntaxError - a number is not a valid keyword argument!
prices = dict(1='one', 2='two')
6 ignores the key-value pairs where the age is equal to or greater than 30. In other words, we filter the original dictionary, selecting only the key-value pairs where the value is less than 30. That’s some powerful stuff!

Create Dictionaries in Python!

In this article, we discussed 5 ways to create dictionaries in Python. We went from the very basics of the dictionary literal

# this works
values = [(1, 'one'), (2, 'two')]
prices = dict(values)

# SyntaxError - a number is not a valid keyword argument!
prices = dict(1='one', 2='two')
9 and the Python
grades = {
    'John': 7.5,
    'Mary': 8.9,
    'James': 9.0,
    # add more lines here …
}
4 constructor, to more complex examples of JSON files, dictionary union operators, and dict comprehensions.

Hope you learned something new. If you want more, be sure to go to LearnPython.com for all things related to Python!

How to create data dictionary in Python?

We can create a dictionary in Python by wrapping a collection of objects in curly brackets and segregating them with a comma. The Dictionary keeps track of a couple of entries, one part of this is called a key, and the other is called the value of the key and is referred to as the key: value pair.

What is dictionaries in Python with example?

Dictionaries are optimized to retrieve values when the key is known. The following declares a dictionary object. Example: Dictionary. capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New Delhi"} Above, capitals is a dictionary object which contains key-value pairs inside { } .

How do you write a dictionary in text Python?

Approach:.
Create a dictionary..
Open a file in write mode..
Here We Use For Loop With Key Value Pair Where “Name” is Key And “Alice” is Value So For loop Goes Through Each Key:Value Pair For Each Pairs..
Then f. write() Function Just Write's The Output In Form Of String “%s”.

How to add dictionary in Python?

Python add to Dictionary using “=” assignment operator If you want to add a new key to the dictionary, then you can use the assignment operator with the dictionary key. This is pretty much the same as assigning a new value to the dictionary.