CS 022A Lecture 10: CSS22A #9: Dictionaries

20 views2 pages
Dictionary
A dictionary is a way of storing pairs of data as key: value
Dictionaries are similar to what their name suggests: an index of words and for
each word a definition
In python, the word is called a key and the definition is a value
Each pair of data consisting of a key and a value is called an item
Keys are associated with the values
When storing items in a dictionary we separate them with commas
The keys and values in a dictionary are not numbered or stored in order
The syntax for creating a dictionary is similar to creating a list but we use curly
brackets rather than square ones
Python dictionary vs physical dictionary
Key ←→ value
Word ← → definition
Looking at the key in a python dictionary is similar to the looking for a particular
word in a physical dictionary
The key is used to look up the value
Values are mapped to keys
Dictionary syntax
Key-value pairs are separated by a colon and the pairs are separated by
commas and all this is enclosed in a pair of curly braces
The keys must be unique values can repeat
For keys: only immutable objects
For values: either immutable or mutable objects can be used
The key-value pairs in a dictionary are not ordered in any manner if you want a
particular order you will have to sort the dictionary before using it
Creating a dictionary
Three methods for creating a dictionary
Method: initialize items during definition: d ={a” :1, b” :2}
Method 2: create an empty dictionary then add key/value pairs to it
Step 1 : create an empty dictionary a pair of curly brackets is
used: emptyDict{ }
Step 2: add elements using square brackets on the left hand side
of an assignment
Method 3: using the built in dict() function to construct a dictionary the
argument to dict() are a sequence of key-value pairs
Dictionary entries are not stored in a particular order
The first pair added in could be the last pair shown
Look up -- retrieve data from the dictionary
The main use for dictionaries is to look up value associated with a particular key
Dictionary elements are accessed via keys
To look up a value use the dictionary name followed by the key in square bracket
Instead of using the index of the element use the key for the value to retrieve
Unlock document

This preview shows half of the first page of the document.
Unlock all 2 pages and 3 million more documents.

Already have an account? Log in

Get access

Grade+
$40 USD/m
Billed monthly
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
10 Verified Answers
Class+
$30 USD/m
Billed monthly
Class+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
7 Verified Answers

Related Documents