Dictionary
A dictionary is a collection in which each element is a
key-value pair.
ex: myGameDict = {
“chess ”: “An indoor game for two players played on a checkerboard”,
“cricket”: ”A game played on a large field with bats, ball, and wickets”,
“football”: ”An outdoor game in which the ball is advanced bypassing“
}
Elements are enclosed with { }.
Each: pair is separated by commas(,).
and are separated by ‘: ’.
Suppose you are reading a book or watching your favorite TV
show and you come across a new word. You don’t know its
meaning; what do you do in that case?
Have you tried using a dictionary? How does it help us?
In a dictionary, words are mapped to their meaning. You can search
for a word and find its meaning.
Note: Here we are referring to online dictionaries. https://kids.britannica.com/kids/browse/dictionary find how the dictionary describes the following games:-
1. chess
2. cricket
3. football
4. tennis
5. basketball
Now, today we shall develop a dictionary of our own
In the above example, the words - chess, cricket, football are the
keys and their descriptions are the values.
Few more facts in the dictionary:
● Duplicate keys are not allowed
● Values are accessed using key
eg: myGameDist[“chess”] refers to “An indoor game for two
players played on a checkerboard”
● To insert a new element to the dictionary,
myGameDist[“Tennis”] =”An outdoor game played using
racket”
The above statement inserts a new key-value pair to the
above dictionary.
● An assignment statement like the above inserts a new
element only if that key is not present in the dictionary
already. If that key is present, it just reassigns the value.
So if we give,
myGameDist[“Cricket”] =” An outdoor played among 2
teams have 11 players each”
The description/value associated with cricket changes.No
new element will be inserted.
● The keys of a dictionary once created cannot be
changed. So we usually go for immutable types as keys.
● The values can be mutable /immutable. So the value can
be int, string, list, or even another dictionary.
Create a game dictionary.
Get the user input name of a game and print its description.
Note: ‘keys()’ and ‘in’ are used to check if a key is
present in the dictionary.
keys() will return you a list of dictionary keys.
myGameDict.keys() will return [“Cricket” ,” Football” ,” Basketball”
,” Chess”]
Create a new entry for Volleyball in the dictionary.
Change the description of cricket in the above dictionary.
The new academic year is starting and you as the store manager are
told to take care of accounts of textbook purchases. As The new python
programmers correct you decide to maintain a dictionary of textbooks and its
cost. Create the dictionary.
Later you found that the,cost of the physics book was entered
wrong. The correct price is 200. Make this change.
Add the cost of 2 more books to the dictionary.
Print cost of the book entered by the user.
Print all the books and their cost.
Comments
Post a Comment