Dictionary Datatype

The dictionary datatype is unlike other datatypes in python, dictionary datatype is used to store key-value pairs to make it more optimized.

The syntax for the dictionary data type is:

dictionary={k1:v1,k2:v2,k3:v3} 
##where k1 =first key , k2=second key, k3=Third key
 ## and v1=first value,v2=second value, v3=Third value

The properties of Dictionary Datatype

  • To represent a group of key values then we will use Dictionary data type
  • Here we can use duplicate values but we cannot use duplicate keys.
  • Insertion order is not preserved and the dictionary is based on hashcode of the keys.
  • Indexing and Slicing concepts are not allowed.
  • For both the keys and values, Heterogeneous objects are allowed
  • Dictionary is a mutable Datatype
  • Dictionary is dynamic in nature
  • The key-values are represented inside the curly braces separated comma.
  • If we try to use the duplicate keys in the dictionary then the old values will be replaced with the new value.

Example:

dictionary={100:"Apple", "A":300, 200:"pooja",  "orange":400, 100:"Pista"}
print(dictionary)

The output is:

dictionary-operator-python-example

If you observe the above output, here we have used the key value 100 two times but the old key value has been replaced with the new key value.

Different ways of Creating a Dictionary Objects

We can Create Dictionary Objects in many ways as follows:

Creating an Empty Dictionary:

We can create an empty dictionary in two ways

dictionary={ }
print(type(dictionary))
dictionry= dict()     #by using dict function
print(type(dictionary))                     

The output is:

creating-empty-dictionry

Creating a Dictionary if we know the data already:

If we know the key-value pairs then we can create a dictionary by separating the key and value by a colon and separating each key-value pairs by comma enclosed with curly braces.

dictionry={100:"banana", 300:"Apple", 400:"plum"}
Creating a Dictionary by converting other datatypes using dict() Function:

The following example demonstrates converting a list of tuple values into a dictionary

info=[('a',100),('b',200),('c',300)]
data=dict(info)
print(data)

The output is:

converting-list-of-tuples-into-dict

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions