INTRO   O

PROBLEM SOLVING AND

PROGRAMMING IN PYTHON

 

(use the Space key to navigate through all slides)

Prof. Andrea Gallegati
tuj81353@temple.edu

Prof. Dario Abbondanza
tuk96119@temple.edu

CIS 1051 - DICTIONARIES

Understanding the

objects    

Playing with Keys and Values

dict

A dictionary is a collection of key-value pairs.

 

  • Created using curly braces,
    person = {"name": "Dario", "age": 30}
     
  • Each entry maps a unique key to a value
     

  • Keys must be immutable types (e.g., strings, numbers, tuples), while values can be any data type
     

  • Dictionaries are mutable, just like lists
     

 

Common dict methods

  • get(key, default=None): Safely access a value, returning default if the key does not exist.
  • keys(): Return a view of all keys.
  • values(): Return a view of all values.
  • items(): Return a view of all (key, value) pairs.
  • pop(key[, default]): Remove the specified key and return its value.
  • update(other_dict): Merge another dictionary’s key-value pairs into the current dictionary.

Functions that are proper of the dict class

Common dict methods

Functions that are proper of the dict class

Iteration

Is commonly used with dictionaries

person = {"name": "Dario",
           "age": 30}

for key in person.keys():
    print(key, person[key])

for key, value in person.items():
    print(key, value)

This was crafted with

A Framework created by Hakim El Hattab and contributors
to make stunning HTML presentations

dictionaries

By Andrea Gallegati

dictionaries

  • 88