Understanding Dictionaries
Dictionary is the most handy data type offered by Python and frequently used when the items are needed to be accessed by special or user defined keys.
Dictionaries are quite similar to the lists in the following ways:
Mutable: Like lists, dictionaries are also mutable,
Can contain any type of data types like lists.
But differ from the lists in the following ways:
Dictionaries do not support numeral indexing like lists do. However, you can access the items with their respective keys.
Keys in dictionaries are of immutable type unlike lists, where keys simply mean the positions of the items.
Dictionary as map
Dictionary consists of collection of the key-value pairs. It works as a map data structures in other programming languages. Dictionary maps the value to its associated key.
Restriction with keys
Like list where positions of the items are unique, dictionary keys are also unique and of immutable type.
Creating Dictionary
Dictionary can be created by enclosing the key-value pairs inside curly braces ( { } ) like:
dict = { key:value, key:value, ….}
Creating name of the books with respective author
books_details = {
“Let us C” : “Yashavant Kanetkar”,
“TCR JAVA” : “Herbert Schildt”,
“Design and Analysis of Algorithms” : “Thomas Cormen”,
“Operating Systems” : “Peter Galvin” }
Dictionary can also be created using built-in dict( ) function:
books_details = dict( [
(“Let us C”, “Yashavant Kanetkar”),
(“TCR JAVA”, “Herbert Schildt”),
(“Design and Analysis of Algorithms”,“Thomas Cormen”),
(“Operating Systems”, “Peter Galvin”),
] )
Accessing Value with key
books_details[ “let us C”]
'Yashavant Kanetkar'
Referring to a key which is not present in the dictionary, Python raises an exception:
books_details[“ abc”]
If you try to use key as mutable type like list, Python raises exception
dict = { [“Python”, “JAVA”, “C”] : “ Programming Languages” }
Updating the existing value of the key
books_details[“Operating Systems”] = “Avi Silberschatz”
books_details
{'Let us C': 'Yashavant Kanetkar', 'TCR JAVA': 'Herbert Schildt', ‘Design and Analysis of Algorithms’ : ‘Thomas Cormen’,‘Operating Systems’ : ‘Avi Silberschatz’ }
Updating is possible because dictionary values are mutable type.
Nice 100 working
ReplyDeleteThank you for the feedback!
DeleteSuperb
ReplyDeleteThank you for the feedback!
DeleteLit stuff
ReplyDeleteThank you for the feedback!
DeleteGood
ReplyDeleteEasily Understandable, Nicely Explained
ReplyDeleteThank you for the feedback!
DeletePerfectly explained, loved it!
ReplyDeleteThanks for the feedback!
DeleteYour Blog are completely remarkable and share worthy. I really appreciate your efforts that you put on this. Keep sharing.
ReplyDeleteC++ Training Institute in South Delhi