Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Dictionaries

Similar presentations


Presentation on theme: "Introduction to Dictionaries"— Presentation transcript:

1 Introduction to Dictionaries
Dictionaries are collections of data which are represented as items. Items are key:value pairs. The values are mutable, the keys are immutable. Mutable means that the values can be changed after the dictionary has been created; the values of items can be changed, items can be appended to or removed from the dictionary, and so forth. Dictionary keys can be integers, strings, or tuples. Dictionary values can be integers, floats, strings, lists, tuples, even dictionaries, or other types of data. If you know a programming language such as Perl or PHP then you are already familiar with associative arrays. Dictionaries are similar to associative arrays in that the keys and values may be of different types. Copyright (c) 2017 by Dr. E. Horvath 1

2 Introduction to Dictionaries
The data in dictionaries is organized for efficient searches based upon a key. You do not have control over the order of the items that are the dictionary are stored in memory. Copyright (c) 2017 by Dr. E. Horvath 2

3 Declaring a dictionary
A dictionary is declared with square brackets: information_dict = {} Notice the naming convention; the name of the dict should end with an underscore followed by the word dict. This convention is not enforced by the Python interpreter, but following this convention will make your code much more readable. You can also declare a dictionary with the items given in the declaration statement: employee_dict = {'2039':'Hakeem Jawal', '1290':'Enzo Sato', '8837':'Lorelei Goldberg','3309':'Duc Park', '1772':'Angela Gambino'} Copyright (c) 2017 by Dr. E. Horvath 3

4 Declaring a dictionary
A dictionary is declared with square brackets: information_dict = {} Notice the naming convention; the name of the dict should end with an underscore followed by the word dict. This convention is not enforced by the Python interpreter, but following this convention will make your code much more readable. You can also declare a dictionary with the items given in the declaration statement: employee_dict = {'2039':'Hakeem Jawal', '1290':'Enzo Sato', '8837':'Lorelei Goldberg','3309':'Duc Park', '1772':'Angela Gambino'} Copyright (c) 2017 by Dr. E. Horvath 4

5 Accessing an item of a dictionary
Let's suppose you have a dictionary of student test scores and you wish to access the items of the dictionary: employee_dict = {'2039':'Hakeem Jawal', '1290':'Enzo Sato', '8837':'Lorelei Goldberg','3309':'Duc Park', '1772':'Angela Gambino'} To retrieve a value of an item from the dictionary you use the key. print(employee_dict['2039']) If you specify a key that is not in the dictionary, a KeyError exception will be thrown. try: print(employee_dict['9246']) except KeyError: print("The key was not found"r) Copyright (c) 2017 by Dr. E. Horvath 5

6 Accessing an item of a dictionary
employee_dict = {'2039':'Hakeem Jawal', '1290':'Enzo Sato', '8837':'Lorelei Goldberg','3309':'Duc Park', '1772':'Angela Gambino'} An alternate way to retrieve a value of an item from the dictionary is to use the get method. This will not throw an exception, even if the key is not in the dictionary. print(employee_dict.get('7852') # returns None Copyright (c) 2017 by Dr. E. Horvath 6

7 Accessing all items in a dictionary: An Example
test_score_dict = {'2039':82,'1290':96.5,'8837':79.3,'3309':85,'1772':100} The items() returns a list of tuples, one element in the tuple represents the key and one element represents the value. bonus = 0.95 for key,value in test_score_dict.items(): new_score = value+bonus print(' ', key,' ',new_score) Copyright (c) 2017 by Dr. E. Horvath 7

8 Accessing keys and values in a dictionary
# keys() returns a dict_keys object # values() returns a dict_values object student_id = test_score_dict.keys() for s in student_id: print(' ', s) test_score = test_score_dict.values() for t in test_score: print(' ', t) Copyright (c) 2017 by Dr. E. Horvath 8

9 Adding a Value in the Dictionary
test_score_dict = {'2039':82,'1290':96.5,'8837':79.3,'3309':85,'1772':100} # Add a new value to the dictionary: test_score_dict['2564'] = 89.6 key = input(“Enter the key”) new_value = float(input(“Enter the new value”)) test_score_dict[key] = new_value Copyright (c) 2017 by Dr. E. Horvath 9

10 Updating Values in the Dictionary
test_score_dict = {'2039':82,'1290':96.5,'8837':79.3,'3309':85,'1772':100} # Update a value to the dictionary: test_score_dict['2564'] = 98.2 # Updating all of the values in the dictionary bonus = 2.95 for key,value in test_score_dict.items(): new_score = value+bonus test_score_dict[key] = new_score print(' ', key,' ',new_score) # Updated specific values in the dictionary test_score_dict.update({'2039':89,'8837':87}) Copyright (c) 2017 by Dr. E. Horvath 10

11 Deleting a Value in the Dictionary
test_score_dict = {'2039':82,'1290':96.5,'8837':79.3,'3309':85,'1772':100} find = input("Enter the key for an item to delete\n") if find in test_score_dict: del test_score_dict[find] value_removed = test_score_dict.pop(find) print("value_removed " + str(value_removed)) Copyright (c) 2017 by Dr. E. Horvath 11

12 Using dictionary functions
grocery_store_dict = {'broccoli':2.65,'squash':3.09,'tomatoes':5.09, 'kohl rabi':6.34,'kale':2.34,'carrots':1.32} The function len returns the collection length. The sum, min, and max can be used for the values. print(grocery_store_dict.get('potato')) print(len(grocery_store_dict)) print(sum(grocery_store_dict.values())) print(min(grocery_store_dict.values())) print(max(grocery_store_dict.values())) Copyright (c) 2017 by Dr. E. Horvath 12

13 Example of values as lists
def main(): employee_dict = {'Hakeem':[2992,330,23,29], 'Enzo':[555,32,4,6,54], 'Lorelei':[77,8787,48,70], 'Duc':[12,304,29894,300]} print('Enzo '+str(employee_dict['Enzo'])) main() Copyright (c) 2017 by Dr. E. Horvath 13

14 Example of different data types for keys and values
#Another example-the keys and values can be of different types def main(): itinerary_dict = {'Belgium':'Tuesday',234: , 901:['Candy Corn', 333, 2.908]} print(str(itinerary_dict)) main() Copyright (c) 2017 by Dr. E. Horvath 14


Download ppt "Introduction to Dictionaries"

Similar presentations


Ads by Google