Dict (Dictionary)
We have covered about
list, tuple, set, frozenset. But all these data types having one common point
that is ‘all contain a group of single objects’. Like
The list contains a
group of single objects within the square brackets,
The tuple contains a
group of single objects within the round brackets or parenthesis,
The set contains a
group of single objects within the curly braces,
The frozenset
contains as a parenthesis with internal sets.
But sometimes our requirement is we want to represent key-value pairs.
Ex: item
number: item name
Ticket
number: person name
If
we want to represent a group of objects as a key-value pair then we can
using this data type. It’s called dict or dictionary. We all know that
general English dictionary. The dictionary has a lot of English words and some
words belonging to some meaning, dict data type also same like.
Example: Ticket
number: person name.
Dict syntax is
{1:one,2:two}.
Game_palyers =
{cricket:rahul,chess:vishnu, tennis:sania}.
game_palyers =
{1:'rahul',2:'vishnu',3:'sania'}
print(type(game_palyers))
<class 'dict'>
#result
game_players =
{1:'rahul',2:'vishnu',3:'sania'} #one type of create the dict
nice_players
={} #
another type of create the dict
nice_players[1] =
'rahul'
nice_players[2] = '
vishnu '
nice_players[3] = '
sania '
print(nice_players)
{1: 'rahul', 2: '
vishnu ', 3: ' sania '} #result
python 3.6x
version and before python 3 version dict data type not ordered type. But after
3.7 version dict data type is ordered type.
It’s most commonly
used data type in python.
Now take this as
example
game_players =
{1:'rahul',2:'vishnu',3:'sania'} here 1 is key and ‘rahul’ is the value.
In 'dict' once we
create the 'dict' data type we can’t change the keys and we can change the
values. If we are trying to create like
(game_players[1] =
krishna) then it’s not showing any error.it’s replaced with rahul to krishna.
Now if you want to
print the game_payers then it’s changed like
game_players =
{1:'krishna',2:'vishnu',3:'sania'}
Imp points:
1. Dict
type represents a group of key-value pairs
2. Dict
type ordered after 3.7x version before it’s not an ordered type.
3. Dict
type not accepted duplicate keys but it’s accepted duplicate values.
4. Heterogeneous objects are allowed.
Heterogeneous means all types of fundamental data types.
5. Dict
type is mutable.
6. Indexing
and slicing not applicable.
Post a Comment