Dictionaries 👷🏼♂️👷🏼♀️
Matched key:value pairs
my_dict = { 'colour':'blue', 'points':20, 'super_factor':3 }
action | code |
---|---|
access a value | my_dict['colour'] |
adding items | my_dict['new_item'] = 'brand new thing' |
modifying items | my_dict['colour'] = 'green' |
removing items | del my_dict['points'] |
method | action |
---|---|
dict.keys() |
lists all the keys in the dict |
dict.values() |
lists all the values in the dict |
dict.items() |
lists all the items in the dict |
dict[key] |
returns the value associated with that key, throws an error if key doesn't exist |
dict.remove[key] |
removes the k:v pair (also del dict[key] does the same thing) |
dict[key] = value |
adds the k:v pair or updates the k:v pair if it already exists in the dict |
Zipping
keys = ['a', 'b', 'c']
vals = [1, 2, 3]
mydict = dict(zip(keys,vals))
mydict
now equals -> {'a':1, 'b':2, 'c':3}