Chapter 9 and 6 Flashcards
(70 cards)
Are dictionaries mutable or immutable?
Mutable
- you can easily add, update and remove elements
Curly brackets {}
Differences between Dictionaries and Lists/Tuples
- each element in a dictionary is a KEY-VALUE pair
{key: value, key: value}
- dictionaries have NO ORDER (they are NOT A SEQUENCE of items)
- therefore, dictionaries have NO INDEXES (instead, retrieve values using KEYS)
Create a new dictionary with has the following keys and values:
Chris 123
Katie 345
Joanne 567
dictNames = dict() #creates an empty dictionary
dictNames = {‘Chris’: 123, ‘Katie’: 345, ‘Joanne’: 567}
Is this appropriate?
myDict = { [1,2,3]: ‘Hi’, ‘Test’: 123 }
NO
Keys must be IMMUTABLE (strings, integers, floats, tuples)
Values can be ANYTHING (including lists)
How do you retrieve a value from a dictionary?
What happens when the key doesn’t exist?
- NOT by indexes (don’t exist because there’s no order)
- use KEYS instead
myDict[key] = value
- if the key doesn’t exist, it’s like the same as when an index doesn’t exit => KeyError
*Therefore, it’s helpful to use:
.get(key, default)
How to test if a key is already in the dictionary?
- use IN and NOT IN operators
if key in myDict.keys():
or
if key in myDict:
Let’s say you have the following dictionary:
myDict = {‘John’: 85, ‘James’: 65, ‘Jacob’: 95}
What does myDict contain if the following is run:
myDict[‘John’] += 5
myDict = {‘John’: 90, ‘James’: 65, ‘Jacob’: 95}
John’s value is UPDATED
There are NO DUPLICATE KEYS in a dictionary
Deleting key-value pair from a dictionary
what happens if that pair doesn’t exist?
del myDict[key]
If the key doesn’t exist => KeyError exception will be raised
Is this allowed?
myDict = {‘abc’: 1, 999: ‘yada yada’, (3,6,9): [3,6,9]}
Yes
Mixed data types are allowed.
As long as KEYS are IMMUTABLE
How do you iterate over all the keys in a dictionary?
for key in myDict.keys()
or
for key in myDict
How do you clear the contents of a dictionary?
myDict.clear()
- results in an empty dictionary {}
Alternatively, just set the variable myDict = {}
How do you get the value associated with a specified key?
myDict[key]
- will raise a KeyError exception if not found –> need IN operator first
or
myDict.get(key, default)
- won’t raise a KeyError exception if not found
- just returns a default value
How do you return all the keys in a dictionary and their values as a sequence of tuples?
myDict.items()
Returns:
dict_items( [ (key, value), (key, value) ] )
*NOT actually a list; merely a dictionary representation
How do you return all the keys in a dictionary as a sequence of tuples?
myDict.keys()
Returns:
dict_keys( [ key, key, key ] )
- you can ITERATE over these as a normal list (even though it’s NOT a list type)
To convert into a list:
list(myDict.keys())
How do you return the value associated with a key and also remove that key-value pair from the dictionary?
What if that key doesn’t exist?
myDict.pop(key, default)
- returns the value associated with key, then removes the key-value pair
- if the key doesn’t exist, return the default (‘Entry not found’)
How do you return a randomly selected key-value pair as a tuple from a dictionary and remove that same key-value pair from the dictionary?
Example application: drawing a card from a standard deck
How can you store the key and value as separate variables?
What if the dictionary is empty?
myDict.popitem()
** NOT popitemS()
Returns: (Key, Value) –> TUPLE
You can use a multiple assignment statement to assign the returned key and value to individual variables:
e.g. k, v = myDict.popitem()
If empty dictionary:
- you can’t pop anything –> KeyError
How do you return all the values in a dictionary as a sequence of tuples?
myDict.values()
Returns: dict_values( [value, value, value] )
- NOT actually a list - it is considered a “view object”
To convert into a list:
list(myDict.values())
Suppose you have the following dictionary:
myDict = {1: 4, ‘Hello’: [1,2]}
What are possible outputs from list(myDict.keys())?
A: [1, ‘Hello’]
B: [‘Hello’, 1]
C: [4, [1,2]]
D: [[1,2], 4]
A and B
- the order of the resulting list is NOT guaranteed from a dictionary!!
Do you need a return statement in functions that takes a dictionary as a parameter and may modify it?
NO
- since dictionaries are MUTABLE like lists, you don’t need a return statement
Given three dictionaries, associated with the variables,canadian_capitals,mexican_capitals, andus_capitals, that map provinces or states to their respective capitals, create a new dictionary that combines these three dictionaries, and associate it with a variable,nafta_capitals.
CANNOT do concatenation with dictionaries
Option 1: Loop through each of the 3 dictionaries to get the key and value, then add key and value to the new dictionary
nafta_capitals = {}
for key in us_capitals:
……nafta_capitals[key] = us_capitals[key]
Option 2: nafta_capitals.update(dictionary)
How do you get the max key in a dictionary?
max(myDict) works
BUT BETTER:
- Get list version of keys
list( myDict.keys() ) - Get first key (stored in index 1), store as maxKey
maxKey = list( myDict.keys() )[0] - Iterate through each key and compare to maxKey. Update maxKey accordingly.
for key in myDict.keys():
….if key > maxKey:
……..maxKey = key
What are sets?
Are they mutable?
Sets store a collectionof elements inside curly brackets
- sets are MUTABLE (like dictionaries and lists)
- recall .add() and .update()
- they are UNORDERED (like dictionaries)
- they contain UNIQUE elements (like dictionary keys)
- elements can be of different data types
How do you create a set with the following elements?
{2,4,’Hello’}
set( [2, 4, ‘Hello’] )
- argument in set() can only be ONE ARGUMENT (no commas or spaces!)
- therefore, to initialize a set with multiple elements, pass objects that contain iterable objects (like a list)
Is this allowed?
set(‘Chris’, ‘Katie’, ‘John’)
NO
- set() takes ONE argument (no commas or spaces)