Classwork:
Two ways to create a dictionary in python:
1.
grocery1 = {'lettuce': 1.99, 'tomato': 0.49, 'onion': 0.35, 'olives': 0.99}
2.
grocery2 = {} grocery2['lettuce'] = 1.99 grocery2['tomato'] = 0.49 grocery2['onion'] = 0.35 grocery2['olives'] = 0.99 grocery2 {'olives': 0.99, 'tomato': 0.49, 'onion': 0.35, 'lettuce': 1.99}
Two ways to insert a new key-value pair to the dictionary:
1.
grocery1['lemon'] = 0.78 grocery1 {'olives': 0.99, 'lemon': 0.78, 'tomato': 0.49, 'onion': 0.35, 'lettuce': 1.99}
2.
grocery1.update({'potato':1.10}) grocery1 {'lemon': 0.78, 'onion': 0.35, 'potato': 1.1, 'olives': 0.99, 'tomato': 0.49, 'lettuce': 1.99}
Two ways to create a list of the keys of the dictionary:
1.
keys = grocery1.keys() keys dict_keys(['lemon', 'onion', 'potato', 'olives', 'tomato', 'lettuce']) for key in keys: print(grocery1[key], end = '-') 0.78-0.35-1.1-0.99-0.49-1.99- print(keys) dict_keys(['onion', 'tomato', 'olives', 'lettuce']) for key in keys: print(key, end = ' ') onion tomato olives lettuce
2.
keys_list = list(grocery1.keys()) keys_list ['lemon', 'onion', 'potato', 'olives', 'tomato', 'lettuce']
Two ways to create a list of values:
1.
values_list = [] for key in keys: values_list += [grocery1[key]] values_list [0.78, 0.35, 1.1, 0.99, 0.49, 1.99]
2.
val_list = grocery1.values() val_list dict_values([0.78, 0.35, 1.1, 0.99, 0.49, 1.99])
More to know:
x = 'lemon' in grocery x True y = 'carrot' in grocery y False
How to delete a key-value entry pair from a dictionary:
grocery1 = {'lettuce': 1.99, 'tomato': 0.49, 'onion': 0.35, 'olives': 0.99} del grocery1['lettuce'] grocery1 {'onion': 0.35, 'tomato': 0.49, 'olives': 0.99}
In edmodo.com
Homework:
Answer the following questions in edmodo.com
1. Do lists allow duplicate elements? what about dictionaries?
adict = {'a':1,'b':2,'a':4} adict {'a': 4, 'b': 2}
2. What are two ways to insert key–> value pairs into a dictionary.
3. Can different ‘types’ of keys be used in the same dictionary?
4. What happens when you try entering a value for a key that is already in the dictionary?
5. Create a scenario in which you would use a dictionary (without using the grocery example from these slides), and explain why you’d use a dictionary rather than a list.
Gota, you were right. Here is another way to add a key-value pair to a dictionary from stackoverflow.com
x = {1:2} print x {1: 2} x.update({3:4}) print x {1: 2, 3: 4}