Dictionaries Flashcards
In Python, what are dictionaries?
Dictionaries are mappings which are a collection of objects that are stored by a key and then an associated value.
Construct a dictionary with two key values.
my_dict = {‘key1’ : ‘value1’, ‘key2 : ‘value2’}
my_dict = {‘key1’:234, ‘key2: [12,23,46], ‘key3’:[‘item0’, ‘item1’ , ‘item2’]}
Call key3 and display the output
my_dict[‘key3’]
[‘item0’ , ‘item1’, ‘item2’]
my_dict = {‘key1’:chair’ , ‘key2’:’table’, ‘key3’:[13,34,72], ‘key4’: [‘car1’, ‘car2’, ‘car3’]}
- Call key4 from my_dict and then call index[1] from the return vaiue.
my_dict[‘key4’]
[‘car1’, ‘car2’, car3’]
my_dict[‘key4’][1]
‘car2’
my_dict = {‘key1’:chair’ , ‘key2’:’table’, ‘key3’:[13,34,72], ‘key4’: [‘car1’, ‘car2’, ‘car3’]}
- Call key4 from my_dict and then call index[1] in uppercase from the return vaiue.
my_dict[‘key4’]
[‘car1’, ‘car2’, car3’]
my_dict[‘key4’][1].upper()
‘CAR2’
create {‘animal’: ‘Dog’, ‘answer’ : 42} from the dictionary d
d = {}
d[‘animal’] = ‘Dog’
d[‘answer’] = 42
d
(rtn = {‘animal’: ‘Dog’, ‘answer’: 42}
car_colour = {}
car_colour[‘blue’] = ‘polo’
car_colour[‘answer’] = 1997
car_colour
{‘blue’ : ‘polo’, ‘answer’ : 1997}
d = {‘car’:{‘blue’ :{‘year’: ‘1997}}}
Grab the value.
d[‘car’][‘blue’][‘year’]
- 1997
what method is used to return a list of all keys?
.keys()
what method is used to grab all values?
.values()
what method is used to return tuples of all items?
.items(()