Dictionary and Sets Flashcards
What is a dictionary?
An object that stores a collection of data.
A dictionary has two parts. What are they?
key
value
How can you locate a specific value
using key.
Webster analogy
words = keys definition = values
Key-Value pairs are often referred as?
Mappings
Why is key-value pairs referred as mappings?
Because each key is mapped to a value
Create a simple dictionary and explain..
lastname = {‘Ryan’: ‘Higa’, ‘Hanna’ : ‘Martin’, ‘Justin : Timber’}
»> lastname
»> lastname [‘Ryan’] –ryan = key
then it gives u value lastname : Higa.
Keys must be what?
immutable objects. cannot be lists
Syntax for adding new elements
phonebook[‘Sakura’] = ‘Tokyo, Japan’
Can you have duplicate keys in the dictionary?
Nope. Even if you do it will just replace.
Syntax for deleting?
del phonebook[“Sakura”]
Syntax for checking if sakura is in the dictionary
if ‘Sakura’ not in phonebook
print(“Sorry not in the set”)
if ‘Sakura’ in phonebook
print(“In the phonebook”)
How do you get the number of elements in a dictionary?
using len function.
Eg. len(phonebook)
How do you create an empty dictionary?
dictionaryname = {} or dict()
syntax for using loop and printing something in a dictionary
for key in phonebook:
print(key) #for key
print(phonebook[key]) # for value
What does the clear method do?
It clears all the elements of the dictionary
phonebook.clear()
What does the get method do?
gets a value from the dictionary.
Will it raise an exception is key is not found?
No, the method returns default.
How to print everything in dictionary
phonebook.items()
How to print only the keys
phonebook.keys()
how to print only the values
phonebook.values()
What is a set?
A set is a collection of unique values and works like a mathematical set.