Dictionaries Flashcards
What types of lists, tuples, and strings can you convert to dicts?
dict([‘a’, ‘b’], [‘c’, ‘d’]) = {‘a’:’b’, ‘c’:’d’}
dict((‘a’, ‘b’), (‘c’, ‘d’)) = {‘a’:’b’, ‘c’:’d’}
dict(‘ab’, ‘cd’) = {‘a’:’b’, ‘c’:’d’}
How to replace dict key x with ‘y’?
dict[x] = ‘y’
Can you have {‘a’ : ‘b’, ‘a’ : ‘c’}?
No, dict keys need to be unique
How do you merge dict x with dict y?
x.update(y)
It’s kinda like list.extend(y)
How to delete a key:value?
del dict[key]
How to delete everything from a dict?
dict.clear()
it’s a dict method
how to see if ‘x’ is in dict?
‘x’ in dict
Gives boolean
How do you get a key without an error function if it isn’t there?
dict.get(key, ‘it’s not there’)
Returns ‘it’s not there’ if key doesn’t exist
How to get all keys in a list?
dict.keys()
How to get all values in a list?
dict.values()
How to get all items in a list as tuple items in a list?
list(dict.items())
Difference between set and tuple?
set = {x, y} tuple = (x, y)
Sets don’t have an order and are ridiculously fast, tuples do but are like lists in that you can’t change them directly
Things to remember about sets
Don't have an order best time (better than linear) can't have more than one of a type of thing in them