Python Dictionaries PDF

Document Details

RightMeter3001

Uploaded by RightMeter3001

ESADE Business School

Tags

python programming dictionaries data structures computer science

Summary

This document provides an introduction to Python dictionaries. It explains how dictionaries work, including key-value pairs, and their usage in data storage and configuration settings. It also demonstrates different ways to iterate through dictionaries and some basic operations. The language used is Python, and the guide covers iterating, data structures, and basic operations using dictionaries.

Full Transcript

Dictionaries Session 8 1 Dictionaries A dictionary in Python is a collection of key-value pairs that are unordered, changeable, and indexed. Each key in the dictionary maps to a corresponding value, which can be of any data type, such as a string, number, list, or another di...

Dictionaries Session 8 1 Dictionaries A dictionary in Python is a collection of key-value pairs that are unordered, changeable, and indexed. Each key in the dictionary maps to a corresponding value, which can be of any data type, such as a string, number, list, or another dictionary. Dictionaries are enclosed in curly braces ({}) and keys and values are separated by a colon (:) my_dictionary = {"key1": "value1", "key2": "value2"} Among others, the main uses of dictionaries in Python are: Data storage: Dictionaries provide an efficient way to store and retrieve data by using keys to access corresponding values. This makes it easier to search and manipulate data than other data structures, such as lists or tuples. Configuration files: Dictionaries are often used to store configuration settings for applications. The keys in the dictionary represent the settings and the values represent the corresponding values for those settings. Comparison of data structures Lists Dictionaries my_list = [1,2,3] my_dict = {“ABC”:10, “DEF”:2} print(my_list) print(my_dict[“ABC”]) Can contain duplicate elements Can’t contain duplicate keys, but can contain duplicate values my_list = 5 my_dict[“ABC”] = 5 my_list = [] my_dict = {} print(my_list(1:2)) Slicing can’t be done Use lists when you a simple, iterable collection of Use dictionaries when you need a logical association elements that is mutable (can add, change or delete key:value pair, and when your data is unordered , elements). changeable and indexed. Forms of iteration over dictionaries (I) For loop to iterate over keys: Using the keys() method to get a list of keys and then iterating over it: For loop to iterate over keys and values: Using the values() method to get a list of values and then iterating over it: Forms of iteration over dictionaries (II) Using the items() method to get a list of tuples (key, value) and then iterating over it: Python script that takes a dictionary of student names and their corresponding grades and adds students with grades greater than or equal to 5 to another dictionary: Basic operations with dictionaries 1. Accessing Elements: dicc['John’] Accesses the value associated with the key 'John'. dicc.get('Maria’) Safely retrieves the value associated with the key 'Maria'. If the key doesn't exist, it returns None. dicc = {'John' : 89 , 'Maria': 33, 'Hannah':89, 'Peter': 36} print(dicc['John']) # Output: 89 print(dicc.get('Maria')) # Output: 33 print(dicc[’Mark’] # Output: KeyError: 'Mark' 2 Adding or Modifying Elements: dicc['Alice'] = 25: Adds a new key-value pair to the dictionary or updates the value if the key already exists. dicc['Alice'] = 25 print(dicc) # Output: {'John': 89, 'Maria': 33, 'Hannah': 89, 'Peter': 36, 'Alice': 25} 3. Removing Elements: del dicc['Peter’] Deletes the key-value pair with the key 'Peter'. dicc.pop('Hannah') Removes the key-value pair with the key 'Hannah' and returns the deleted value. del dicc['Peter'] print(dicc) # Output: {'John': 89, 'Maria': 33, 'Hannah': 89} dicc.pop(‘Hannah’) # Output : 89 4. Dictionary Length: len(dicc) - Returns the number of key-value pairs in the dictionary. print(len(dicc)) # Output: 3 5. Checking Key Existence: 'John' in dicc: Checks if the key 'John' exists in the dictionary and returns True or False. print('John' in dicc) # Output: True 6. Mathematical Operations: You can perform mathematical operations on dictionary values. For example: dicc['John’] = dicc['John’] + 1 : Increases John's age by 1. Example Write Python script that takes a dictionary of student names and their corresponding grades and adds students with grades greater than or equal to 5 to another dictionary:

Use Quizgecko on...
Browser
Browser