Python Program To Create A Dictionary With A Dictionary Literal


Dictionaries are used to store data values in key:value pairs like maps (which unlike other data types holds only a single value as an element). key:value is provided in dictionaries to make it more effective.

Keys are unique. Dictionary key must be unique. So, no duplicate values are allowed in dictionaries. Dictionaries items are ordered, changeable, immutable. Changeable means here is that, we can add or remove items after the dictionaries are created.

In python, dictionaries are defined as object with the data type ‘dict’. The values in dictionaries items can be of any data type like string, integer, Boolean and list. For determining the how many items a dictionary contains, we use len() function.

Dictionaries keys are case sensitive that is, same key name but with the different case are treated as different keys in python dictionaries.

How to Create a Dictionary with Dictionary Literals?

We can create a dictionary by using curly brackets {}. By placing elements inside curly bracket {} separated the key values by using colon (:) and with commas, between each pair. Dictionaries can consist of integers, strings, Boolean, and list. These types of dictionaries are known as mixed dictionary.

Here, these curly brackets{},colons (:),comma (,) are literals.

Python provides the built in function dict() method is used to create dictionary. The empty curly braces {}is used to create empty dictionaries.

Example

Here, in this program we have created dictionaries by using curly braces {} and key pair values separated by colons (:). Dictionary “a” have integers and strings in it. Dictionary “b” consists of integers only and likewise “c” consists of strings and list in it. Dictionary “d” is empty dictionary.

a= {1:'rose',2:'lily',3:'jasmine'}
b= {1:5,3:7,8:6,9:4}
c= {'spider':'man','captain':'america', 'iron': ["tony","starks"]}
d= {}
print(a)
print(b)
print(c)
print(d)

Output

{1: 'rose', 2: 'lily', 3: 'jasmine'}
{1: 5, 3: 7, 8: 6, 9: 4}
{'spider': 'man', 'captain': 'america', 'iron': ['tony', 'starks']}
{} 

Types of Dictionaries

There are four types of dictionaries in python −

  • Ordered dictionaries

  • Default dictionaries

  • Chain map

  • Counter

Ordered Dictionaries

In this type of dictionaries, keys are ordering which maintains the elements in the inserted order. The only difference between dict() and ordereddict() is that, ordereddict() preserves the order in which keys are inserted. Whereas dict doesn’t track the insertion order.

Example

Here, in this program we have imported ordereddict() for creating ordered dictionary. And we observe that order of output is same as that of order of insertion.

from collections import OrderedDict
a= OrderedDict()
a[1]= "apple"
a[2]= "mango"
a[3]= "cherry"
for key,value in a.items():
   print(key,value)

Output

1 apple
2 mango
3 cherry

Default Dictionary

Default dictionaries is a container like dictionaries present in module collection. In these types of dictionaries default values of keys are given for non-existing keys. For example −

Example

Here, in this program we have imported defaultdict() for creating default dictionary. And we observe that output comes as not existing for non-existing keys.

from collections import defaultdict
def def_value():
   return "not existing"
a=defaultdict(def_value)
a[1]= "hello"
print(a[2])

Output

Not existing

Chain Map

It is a container which combines multiple dictionaries into single unit. It is present in collections library. Maps() returns the corresponding keys along with values of corresponding dictionaries. For example −

Example

Here, in this program we have imported ChainMap() for creating chainmap. The chainmap() added two list and converted it into one.

from collections import ChainMap
a= {1:'apple',2:'cherry'}
b= {3:'feed', 4:'dogs'}
c= ChainMap(a,b)
print(c)

Output

ChainMap({1: 'apple', 2: 'cherry'}, {3: 'feed', 4: 'dogs'})

Counter()

It is a collection where elements are stored as dictionary keys and their count are stored as dictionaries value. Counter() is for calculating the frequency of words in a sentence.

Example

Here, in this program we have imported Counter() for creating Counter dictionary . The Counter() split the sentence and converted it into dictionary.

from collections import Counter
l= 'an apple a day keeps doctor away'
a= Counter(l.split())
print("counter dict:")
print(a)

Output

counter dict: 
Counter({'an': 1, 'apple': 1, 'a': 1, 'day': 1, 'keeps': 1, 'doctor': 1, 'away': 1})

Conclusion

In this article, we have discussed how to create dictionaries with literals and types of dictionaries briefly.

Updated on: 24-Apr-2023

309 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements