Cool Computer Science Thing of the Day
Reading Questions
Quiz
Dictionaries
- Lists are ordered collections, data is access according to where it is located (using the index operator)
- Dictionaries are unordered, so when creating a dictionary a ‘look up’ or key must be specified for each value - a_dict = {1: 'one', 3: 'three'} print(a_dict[1])
- They are called dictionaries because they are like language dictionaries, which associate words with definitions
- The keys can be any immutable type, the values can be any type - a_dict = {'butyraceous': 'buttery', 'inutile': 'no use'} print(a_dict['butyraceous'])
- Note, you can only look up using keys, not values - a_dict = {'butyraceous': 'buttery', 'inutile': 'no use'} print(a_dict['buttery']) # an error there is no key buttery
- Dictionaries are mutable
- Can change a value by assigning - a_dict = {'butyraceous': 'buttery', 'inutile': 'no use'} a_dict['butyraceous'] = 'like butter' print(a_dict['butyraceous'])
- Can create new entries by assigning to keys that are not already in the dictionary - a_dict = {'butyraceous': 'buttery', 'inutile': 'no use'} a_dict['Pickwickian'] = 'odd or unusual' print(a_dict['Pickwickian'])
- Can remove from a dictionary by using del - a_dict = {'butyraceous': 'buttery', 'inutile': 'no use'} del a_dict['butyraceous'] print(a_dict['butyraceous']) # an error
Dictionary Iteration
- Can iterate over the keys of a dictionary - a_dict = {'butyraceous': 'buttery', 'inutile': 'no use'} for key in a_dict: print(a_dict)
- Can iterate over the values, by using the keys - a_dict = {'butyraceous': 'buttery', 'inutile': 'no use'} for key in a_dict: print(a_dict[key])
- Note, the order of keys during iteration is not easily predictable and may change
- The dictionary is stored in a form that makes access fast
- If you need to iterate in an order, can create a list of keys, order the list, and use it to iterate - a_dict = {'butyraceous': 'buttery', 'inutile': 'no use'} keys = list(a_dict.keys()) keys.sort() for i in range(len(keys)): key = keys[i] print(key, ":", a_dict[key])
String Split
    a_string = 'this is a string'
    a_list = a_string.split()
    print(a_list)Lab
- Queue
- lab25