Python Dictionary Introduction | Why to use dictionary | with example


Python Dictionary Introduction | Why to use dictionary | example of dictionary

Python Dictionary

Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Key value is provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’.

 

A Dictionary in Python works similar to the Dictionary in a real world. Keys of a Dictionary must be unique and of immutable data type such as Strings, Integers and tuples, but the key-values can be repeated and be of any type.

 

Note – Keys in a dictionary doesn’t allows Polymorphism.

 Creating a Dictionary

In Python, a Dictionary can be created by placing sequence of elements within curly {}braces, separated by ‘comma’. Dictionary holds a pair of values, one being the Key and the other corresponding pair element being its Key:value. Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable.

 

Dictionary can also be created by the built-in function dict(). An empty dictionary can be created by just placing to curly braces{}.

 

Note – Dictionary keys are case sensitive, same name but different cases of Key will be treated distinctly.

Why use dictionary ?

Because of limitations of list , lists are not

enough to represent real data

 Example

user=[‘pramod’,22,[‘Ravi’,21],[‘Vijavy’,20]]
This list contains user name ,age,favourate movies,

etc you can do this but this is not good way to do

in this

Q – What are the dictionaries

Ans – unordered collections of data in kay :

value pairs.

How to create dictionaries

First method to create ——>

user = {‘name’ : ‘pramod’,‘age’: 22}
print(user)
print(type(user))

second method ———–>

user1 = dict(name = ‘pramod’ , age = 22)
print(user1)

Python Dictionary Introduction | Why to use dictionary | with example

Have any Question or Comment?

Leave a Reply

Your email address will not be published. Required fields are marked *

Domain & free Hosting

Categories

You have successfully subscribed to myprogrammingschool

There was an error while trying to send your request. Please try again.

My Programming School will use the information you provide on this form to be in touch with you and to provide updates and marketing.