Docsity

Nested Data Structures and Built-ins in Python, Lecture notes of Data Structures and Algorithms

Partial preview of the text

Download Nested Data Structures and Built-ins in Python and more Lecture notes Data Structures and Algorithms in PDF only on Docsity!

Nested Data Structures

CS106AP Lecture 15

Roadmap

Programming Basics^ The Console Images Data structures Midterm Graphics Object-Oriented Programming Everyday Python

Life after CS106AP!

Day 1!

Today’s questions How can we store more information and add more structure to our data?

Today’s topics

  1. Review
  2. Built-ins
  3. Nested data structures Lists Dictionaries
  4. What’s next?

Big Picture: Dictionaries + Uniqueness

● A key will only be associated with one value ○ no duplicate keys! ● A dictionary can have multiple values that are the same. dict ‘hansa’ ‘kandula’ ‘lumpy’ ‘surus’ 3 3 1 3 keys values

Accessing a Dictionary’s Keys

d = {‘Gates’: 23, ‘MemChu’: 116, ‘Tresidder’: 57} d.keys() dict_keys(['Gates', 'MemChu', 'Tresidder']) iterable collection of all the keys. iterable means it can be used in foreach

Accessing a Dictionary’s Values

d = {‘Gates’: 23, ‘MemChu’: 116, ‘Tresidder’: 57} list(d.values()) [23, 116, 57] we are using list() to convert d.values() into a list

Looping over a Dictionary’s Keys

d = {‘Gates’: 23, ‘MemChu’: 116, ‘Tresidder’: 57} for building in d.keys(): ... print(building) Gates MemChu Tresidder we can use foreach on the dictionary’s keys!

Looping over a Dictionary’s Keys and Values

d = {‘Gates’: 23, ‘MemChu’: 116, ‘Tresidder’: 57} for building, age in d.items(): ... print(building, ‘is’, age, ‘years old.’) Gates is 23 years old. MemChu is 116 years old. Tresidder is 57 years old. items() gives us key, value pairs

Printing with sep=

d = {‘Gates’: 23, ‘MemChu’: 116, ‘Tresidder’: 57} for building, age in d.items():

... print(building, age, sep=‘: ’) Gates: 23 MemChu: 116 Tresidder: 57 sep is an optional argument like end!

Getting a Sorted List of Keys

d = {‘Gates’: 23, ‘Tresidder’: 57, ‘MemChu’: 116} sorted(d.keys()) ['Gates', 'MemChu', 'Tresidder'] sorted() returns a list in alphabetical order!

Retrieving Min/Max Values

d = {‘Gates’: 23, ‘MemChu’: 116, ‘Tresidder’: 57} min(d.values()) 23 max(d.values()) 116 returns the smallest element! returns the biggest element!

Examples of Built-ins

print() input() str() int() float() len() open() list() sorted() max() min()

Built-ins with Lists