
Understanding Python Dictionaries: Key Concepts and Examples
Discover the fundamentals of Python dictionaries, including how they work, their key characteristics, manipulation options, and handling duplicate values. Explore insightful examples to grasp the concepts effectively.
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
Objectives O This chapter introduces 1. Introduction to dictionary How to use dictionary 2. 2
Dictionary O Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys O Dictionaries are used to store data values in key key: :value value pairs with the requirement that the keys are unique (within one dictionary) O A dictionary is a collection which is ordered, changeable, and do not allow duplicates. 3
Dictionary O A pair of braces creates an empty dictionary: {} O Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary O This is also the way dictionaries are written on output 4
Example thisdict ={ "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict) Dictionary items are ordered, changeable, and does not allow duplicates Dictionaries are ordered, which means that the items have a defined order, and that order will not change As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created 5 Dictionaries cannot have two items with the same key
Example thisdict ={ "brand": "Ford", "model": "Mustang", "year": 1964, "year": 2023 } print(thisdict) Duplicate values will overwrite existing values Duplicate values will overwrite existing values 6
Example thisdict ={ "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict["brand"]) Print the "brand" value of the dictionary 7
Another Example print(d1['A']) #output 1 print(d2['D']) #output 4 print(d3[1] + d3[2]) #output helloHi! d1 = {} d1['A'] = 1 # d1[key] = value d1['B'] = 2 d2 = { C :3, D :4} # Another way for initialization d3 = {} d3[1] = 'hello' #key (or value) can be integer or string d3[2] = 'Hi!' 8
Keys and Values O Dictionary keys must be of an immutable type O Strings and numbers are the two most commonly used data types as dictionary keys O We can also use tuples as keys but they must contain only strings, integers, or other tuples # string keys dict_a = {"Param1": "value1", "Param2": "value2"} print(dict_a) #{'Param1': 'value1', 'Param2': 'value2'} # tuple keys dict_b = {(1, 10): "value1", (1,20): "value2"} print(dict_b) #{(1, 10): 'value1', (1, 20): 'value2'} tuple info 9
Keys and Values O The values in dictionary items can be of any data type # key examples for string, int, boolean, and list data types thisdict ={ "brand": "Ford", "electric": False, "year": 1964, "colors": ["red", "white", "blue"] } 10
Keys and Values O The values in dictionary items can be of any data type # key example for a self-defined class class Person: def __init__(self, name): self.name = name def Say_Hello(self): print('Hello. My name is ' + self.name + '.') members = {1001: Person("John"), 1002: Person("Jane"), 1003: Person("Emily")} print(members[1001].name) # John members[1001].Say_Hello() # Hello. My name is John. 11
Difference between List and Dict list list use brackets [] L1 = [] L1 = [value1, value2......] L1.sort() L1.remove(value) dict dict use braces {} D1 = {} D1 = {key1:value1 , key2:value2......} Sort a Dictionary with the sorted() del D1[key] Empty list or dict Initialization Sorting Delete data 12
Dictionary Methods O dict.clear dict.clear() () Removes all the elements from the dictionary O dict.copy dict.copy() () Returns a copy of the dictionary ex: D2 = D1.copy() O dict.pop(key) dict.pop(key) Removes the element with the specified key O dict.keys dict.keys() () Returns a list containing the dictionary s keys O dict.values dict.values() () Returns a list of all the values in the dictionary O dict.items dict.items() () Returns a list containing a tuple for each key value pair 13
Sorting O We can use the sorted() method sorts iterable data such as lists, tuples, and dictionaries O The sorted() method will put the sorted items in a list # the sorted() arranged the list below in alphabetical order persons = ['Chris', 'Amber', 'David', 'El-dorado', 'Brad', 'Folake'] sortedPersons = sorted(persons) print(sortedPersons) # Output: ['Amber', 'Brad', 'Chris', 'David', 'El-dorado', 'Folake'] 14
Sorting O We can use the sorted() method sorts iterable data such as lists, tuples, and dictionaries O The sorted() method will put the sorted items in a list # the sorted() method sorts the numbers in the tuple below in ascending order numbers = (14, 3, 1, 4, 2, 9, 8, 10, 13, 12) sortedNumbers = sorted(numbers) print(sortedNumbers) # Output: [1, 2, 3, 4, 8, 9, 10, 12, 13, 14] 15
Sorting O We can use the sorted() method sorts iterable data such as lists, tuples, and dictionaries O The sorted() method will put the sorted items in a list # If we use the sorted() method with a dictionary, only the keys will be returned # and as usual, it will be in a list my_dict = { 'num6': 6, 'num3': 3, 'num2': 2, 'num4': 4, 'num1': 1, 'num5': 5} sortedDict = sorted(my_dict) print(sortedDict) # ['num1', 'num2', 'num3', 'num4', 'num5', 'num6'] 16
Parameters of the sorted() Method O The sorted() method can accept up to 3 parameters O iterable the data to iterate over. It could be a tuple, list, or dictionary O key an optional value, the function that helps you to perform a custom sort operation O reverse another optional value. It helps you arrange the sorted data in ascending or descending order O The key parameter is what we ll pass into the sorted() method to get the dictionary sorted by value 17
Sorting by Values O Pass the dictionary to the sorted() method as the first value O Use the items() method on the dictionary to retrieve its keys and values O Write a lambda function to get the values retrieved with the items() method footballers_goals = {'Eusebio': 120, 'Cruyff': 104, 'Pele': 150, 'Ronaldo': 132, 'Messi': 125} # x[0] is the key and x[1] is the value # While using x[1], we can sort the dictionary by values sorted_footballers_by_goals = sorted(footballers_goals.items(), key=lambda x:x[1]) print(sorted_footballers_by_goals) # [('Cruyff', 104), ('Eusebio', 120), ('Messi', 125), ('Ronaldo', 132), ('Pele', 150)] 18
Converting the Resulting List to a Dictionary O To convert the resulting list to a dictionary, we just need to pass the variable saving the resulting list into the dict() method footballers_goals = {'Eusebio': 120, 'Cruyff': 104, 'Pele': 150, 'Ronaldo': 132, 'Messi': 125} sorted_footballers_by_goals = sorted(footballers_goals.items(), key=lambda x:x[1]) converted_dict = dict(sorted_footballers_by_goals) print(converted_dict) # Output: {'Cruyff': 104, 'Eusebio': 120, 'Messi': 125, 'Ronaldo': 132, 'Pele': 150} 19
Sorting the Dictionary by Value in Ascending or Descending Order O The sorted() method accepts a third value called reverse O reverse with a value of True will arrange the sorted dictionary in descending order footballers_goals = {'Eusebio': 120, 'Cruyff': 104, 'Pele': 150, 'Ronaldo': 132, 'Messi': 125} sorted_footballers_by_goals = sorted(footballers_goals.items(), key=lambda x:x[1], reverse=True) converted_dict = dict(sorted_footballers_by_goals) print(converted_dict) # Output: {'Pele': 150, 'Ronaldo': 132, 'Messi': 125, 'Eusebio': 120, 'Cruyff': 104} 20
Sorting by Keys d1 = {} d1['a'] = 1 d1['b'] = 2 d1['aa'] = -7 d1['bb'] = 20 d1['abc'] = 4 d1['d'] = -10 for k in d1.keys(): print(k, d1[k]) print('---------------') for k in sorted(d1.keys()): print(k, d1[k]) print('---------------') for k in sorted(d1.keys(), reverse = True): print(k, d1[k]) 21
Example(1) scores = {} result_f = open("results.txt") for line in result_f: (name, score) = line.split() # line.split() = [ Johnny , 8.65 ] for the first line # Assume that the scores in result.txt are unique scores[score] = name result_f.close() Results.txt print("The top scores were:") for each_score in sorted(scores.keys(), reverse = True): print('Surfer ' + scores[each_score] + ' scored ' + each_score) Output 22
Example(2) def find_details(id2find):# find personal data via id surfers_f = open("surfing_data.txt") for each_line in surfers_f: s = {} (s['id'], s['name'], s['country'], s['average'], s['board'], s['age']) = each_line.split(";") #split the string by semicolon if id2find == int(s['id']): surfers_f.close() return(s) surfers_f.close() return({}) #no such id surfing_data.txt 23
Example(2) # main program while 1: lookup_id = int(input("Enter the id of the surfer: ")) surfer = find_details(lookup_id) if surfer: # return(s) print("ID: " + surfer['id']) print("Name: " + surfer['name']) print("Country: " + surfer['country']) print("Average: " + surfer['average']) print("Board type: " + surfer['board']) print("Age: " + surfer['age']) else: # return({}) print( Wrong id.") Output 24
Exercise O Please design a program that can read a text file that includes student names and their scores. The program will list all information sorted in descending order of the scores if the user inputs a ; otherwise, if the user inputs b , the information will be listed in alphabetical order of the names Input file Output 25
O : O https://docs.python.org/3/library/stdtypes.ht ml#typesmapping O https://www.tutsmake.com/python-3- dictionary-methods-clear-copy-pop-get-etc/ O https://www.freecodecamp.org/news/sort- dictionary-by-value-in- python/#howtosortdatawiththesortedmethod 26
Tuples O Tuples are used to store multiple items in a single variable O A tuple is a collection which is ordered and unchangeable unchangeable O Tuples are written with round brackets thistuple = ("apple", "banana", "cherry") print(thistuple) 27
Tuples O Allow Duplicates O Since tuples are indexed, they can have items with the same value thistuple = ("apple", "banana", "cherry", "apple", "cherry") print(thistuple) O To determine how many items a tuple has, use the len() function thistuple = ("apple", "banana", "cherry") print(len(thistuple)) 28
Tuples O To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple thistuple = ("apple",) print(type(thistuple)) # <class 'tuple'> #NOT a tuple thistuple = ("apple") print(type(thistuple)) # <class 'str'> 29
Tuples O A tuple can contain different data types # A tuple with strings, integers, and boolean values tuple1 = ("abc", 34, True, 40, "male") O It is also possible to use the tuple() constructor to make a tuple # note the double round-brackets thistuple = tuple(("apple", "banana", "cherry")) print(thistuple) # ('apple', 'banana', 'cherry') 30
O : O https://www.w3schools.com/python/python_ tuples.asp 31