Ch 6. Flashcards
What is a dictionary in python?
A collection of key-value pairs, where each key is connected to a value, and you can use a key to access the value associated with that key.
Note: value can be any of the data types
Generic dictionary looks like?
dictionary_name = { “a”: “one”, “b” : “two}
where a and b are keys
and one and two are their associated values
How do you print the associated value of a key?
print(dictionary_name[key])
where the value should be printed
How do you add new key-value pairs to a dictionary?
dictionary_name[“key”] = “value”
When do you typically start off with an empty dictionary?
When storing user-supplied data or when you write code that generates a large number of key-value pairs automatically.
How do you modify values in a dictionary?
Same as adding new key values but of course you are just changing the value
How do you remove a key value pair?
using the del statement: del dictionary_name[“a”]
What is the get() method used for?
To set a default value that will be returned if the requested key doesn’t exist.
How is get() used?
value = foo.get(key)
Value will either be the “value” or None
What are the different ways to loop through a dictionary?
Can loop through all of the dictionary’s key value pairs, through its keys, or through it’s values.
What does the method items() do?
Returns a list of key value pairs
How do you loop through all key value pairs?
for key, value in dictionary_name.items():
What is the keys() method useful for?
To iterate the keys of the dictionary
How do you loop through all the keys in a dictionary?
for key_name in dictionary_name.keys()
What else can you do with the keys() method?
Check if a key is in a dictionary