Make Dictionary Python | Basics

Making a dictionary is as simple just do place elements inside curly braces {} separated by commas. An element has a key and a corresponding value that is expressed as a pair (key: value).

Empty Dictionary:

# empty dictionary
my_dict = {}

Example Make Python Dictionary

Simple example code.

employees = {
    "1": "John",
    "2": "Nell",
    "3": "Tim"
}

print(employees)
print(type)

Output:

Make Dictionary Python

You can also make a dictionary using the dict() function.

Example making dictionary with integer keys.

my_dict = dict({1: 'apple', 2: 'ball'})

print(my_dict)

Output: {1: ‘apple’, 2: ‘ball’}

More Examples

# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
print(my_dict)

# from sequence having each item as a pair
my_dict = dict([(1, 'apple'), (2, 'ball')])
print(my_dict)

Output:

{‘name’: ‘John’, 1: [2, 4, 3]}
{1: ‘apple’, 2: ‘ball’}

Do comment if you have any doubts and suggestions on this Python dictionary topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.