Dictionaries Flashcards
What is a dictionary?
A set of key value pairs. Keys are unique. They are mutable (can be changed).
How can you retrieve the value from a dictionary?
bad_guys = {“batman”: “bane”, “daredevil”: “kingpin”, “x-men”: “apocalypse”}
who is batman’s bad guy?
bad_guys[“batman”]
will return:
“bane”
what happens if you specify a key that is not in the dictionary?
KeyError
How do you replace a value in the dictionary?
bad_guys = {“batman”: “bane”, “daredevil”: “kingpin”, “x-men”: “apocalypse”}
replace “apocalpyse” with “juggernaut”
bad_guys[“x-men] = “juggernaut”
How can you delete a key in a dictionary?
bad_guys = {“batman”: “bane”, “daredevil”: “kingpin”, “x-men”: “apocalypse”}
delete batman
del bad_guys[“batman”]
True or False - You can access dictionaries with index #s.
False. You cannot, you will get KeyError
How do you call a specific list value within a dictionary?
amit_linkedIn = {‘fname’:’Amit’, ‘lname’:’Shah’, ‘past_jobs’: [‘gcg’, ‘om’, ‘psc’]}
Return OM
amit_linkedIn[‘past_jobs’][1]
How do you call a specific dictionary value within a dictionary?
amit_linkedIn = {‘fname’:’Amit’, ‘lname’:’Shah’, ‘past_jobs’: [‘gcg’, ‘om’, ‘psc’], ‘transportation’:{‘car’:’subaru’, ‘subway’:’A’, ‘cab’:[‘uber’, ‘lyft’]}}
Return car
amit_linkedIn[‘transportation’][‘car’]
True or False - Keys can be used more than once.
False
True or False - dictionaries cannot be keys
True
True or False - lists can be keys
False
How can you check for the existence of keys within a dictionary?
amit_linkedIn = {‘fname’:’Amit’, ‘lname’:’Shah’, ‘past_jobs’: [‘gcg’, ‘om’, ‘psc’]}
Check for past jobs
> > > ‘past_jobs’ in amit_linkedIn
True
> > > amit_linkedIn.get(‘past_jobs’)
[‘gcg’, ‘om’, ‘psc’]
What does the dictionary.get() function do?
It will provide you with the value for the key that is provided in the get function.
What does the dictionary.items() function do?
It lists out the key value pairs in tuple form.
What does the dictionary.keys() function do?
Lists out the keys