Sets – Operations, online

Six activities your students do on their own devices. See who's finished, and their scores.

Sets – Operations in one minute

What students need to know

people[0] gets the first dict, then ['name'] gets its name value. d['nums'] returns the list, then .append() adds to it.

Think of it as a table — each dict is a row with named columns. Lists hold multiple records; dicts give each record named fields.

Mistakes students make

  • people is a list: must index first: people[0]['name'].
  • Dicts use keys not indices. Use ['name'] not [0].
  • Lists use .append(), not .add() (that's for sets).
  • Missing square brackets: this creates a tuple, not a list.
PREVIOUS · MODULE 40Sets – Basics
YOU ARE HERE · MODULE 41Sets – Operations
NEXT · MODULE 42Nested Lists

Discover other journeys with this module

What students will learn in this module

Every question in Module 41

Quick questions

  1. What is a list of dictionaries?AA list where each item is a dictionaryBA dictionary of lists
  2. people = [{'name':'Al'}]\npeople[0]['name'] returns?A{'name':'Al'}B'Al'
  3. d = {'items': [1,2,3]}\nd['items'][0] returns?A1B[1, 2, 3]
  4. Why combine lists and dicts?ATo store structured recordsBFor faster code
  5. How do you add a dict to a list of dicts?A.add({'key': 'val'})B.append({'key': 'val'})

Key terms

Students type the meaning of:

  • List of dicts
  • list[i]['key']
  • Dict with list value
  • d['key'][i]

Match the pairs

people = [{'name':'Ali'}]
print(people['name'])
Match it to what it does
d = {'tags': ['a','b']}
print(d['tags']['a'])
Match it to what it does
people = [{'name':'Ali'},{'name':'Bo'}]
people[0]['name']
Match it to what it does
d = {'nums': [1,2,3]}
d['nums'].append(4)
Match it to what it does
p = [{'n':'Ali'},{'n':'Bo'}]
for x in p:
    print(x['n'])
Match it to what it does
d = {'c':['r','g']}
print(d['c'][1])
Match it to what it does

Fill in the blanks

  1. people = [{'name': 'Alice'}]
    print(people[_]['name'])
  2. d = {'items': [1, 2, 3]}
    print(d['items'][_])
  3. people = []
    people.______(  {'name': 'Bob'}  )
  4. for person __ people:
        print(person['name'])
  5. student = {'scores': [90, 85]}
    student['scores'].______(95)

Spot the error

Question 1

Apeople = [{'name': 'Alice'}]Bgreeting = people['name']Cprint('Hello,', greeting)Dprint('Done')

Question 2

Apeople = [{'name': 'Alice'}]Bgreeting = people[0][0]Cprint('Hello,', greeting)Dprint('Done')

Question 3

Ad = {'items': [1, 2]}Bd['items'].add(3)Cprint('Items:', d['items'])Dprint('Done')

Question 4

Apeople = {'name': 'Alice'}, {'name': 'Bob'}Bfirst = people[0]['name']Cprint('First:', first)Dprint('Count:', len(people))

Question 5

Ad = {'scores': [90, 85]}Bprint(d.scores[0])