Python Create Dictionary

Create Dictionary in Python

In this tutorial, we are going to focus on different ways to create a dictionary in Python.

By now you might have already know what a dictionary is. Let us see how to create one.

Following are some of the ways to create a Dictionary in Python.

1. Create a Dictionary through Initialisation

You can initialize a set of key-value pairs to create a dictionary.

Key-value pairs are of the form key:value, separated by comma. And set means, enclosing in curly braces.

In the following example, we will create a dictionary through initialization and print the dictionary.

Python Program

myDict = {1:'foo', 2:'bar', 3:'moo'}

print(type(myDict))
print(myDict)
Run Code Copy

Output

<class 'dict'>
{1: 'foo', 2: 'bar', 3: 'moo'}

2. Create Dictionary using dict() built-in function

We can build a Dictionary in Python from sequence of key-value pairs.

dict([(key1, value1), (key2, value2), (key3, value3)])

Consider the following sequence.

[(1, foo), (2, bar), (3, moo)]

In the following program, we shall pass the above sequence to dict() constructor. Then it returns a Dictionary with key:value pairs formed from the sequence of key-value pairs.

Python Program

myDict = dict([(1, 'foo'), (2, 'bar'), (3, 'moo')])

print(type(myDict))
print(myDict)
Run Code Copy

Output

<class 'dict'>
{1: 'foo', 2: 'bar', 3: 'moo'}

3. Create Dictionary by passing keyword arguments to dict()

If keys are simple strings, you can specify key:value pairs as keyword arguments to dict() constructor as shown below.

dict(key1=value1, key2=value2, key3=value3)

In the following program, we shall pass keyword arguments, to dict() constructor, formed from key:value pairs and create a dictionary.

Python Program

myDict = dict(a='foo', b='bar', c='moo')

print(type(myDict))
print(myDict)
Run Code Copy

Output

<class 'dict'>
{'a': 'foo', 'b': 'bar', 'c': 'moo'}

Please note that you can use this method, only if the keys adhere to the rules of naming a variable.

4. Create Dictionary using Dictionary Comprehensions

You can also create a Dictionary from dict comprehension.

In the following program, we will create a dictionary with a number as key and its cubed-value as value.

Python Program

def someThing(x):
	x = x**3
	return x

myDict = {x: someThing(x) for x in (5, 8, 9, 12)} 

print(type(myDict))
print(myDict)
Run Code Copy

Output

<class 'dict'>
{5: 125, 8: 512, 9: 729, 12: 1728}

Summary

In this tutorial of Python Examples, we learned how to create a dictionary through different ways, with the help of well detailed examples.

Code copied to clipboard successfully 👍