Python Programming

Lecture 4 Dictionaries, Tuples

4.1 Dictionaries

  • A dictionary is like a list, but more general. In a list, the index positions have to be integers; in a dictionary, the indices can be (almost) any type.

  • 
    >>> x = {} #This is False
    >>> print(x)
    {}
    
  • You can think of a dictionary as a mapping between a set of indices (which are called keys) and a set of values.

  • 
    >>> x['one'] = 'apple'
    >>> print(x)
    {'one': 'apple'}
    
  • In general, the order of items in a dictionary is unpredictable.

  • 
    >>> x = {'one':'apple','two':'banana','three':'orange'}
    >>> print(x)
    {'one':'apple','three':'orange','two':'banana'}
    
    >>> print(x['two'])
    'banana'
    
    >>> len(x)
    3
    
  • Adding New Key-Value Pairs

  • 
    >>> alien = {}
    >>> alien['color'] = 'green'
    >>> alien['point'] = 5
    >>> print(alien)
    {'color': 'green', 'points': 5}
    
  • To create a dictionary, start with an empty one, and add the key-value pairs. The keys should be immutable and there is no repeated key. Lists cannot be keys in the dictionary.

  • Modifying Values in a Dictionary

  • 
    >>> alien['color'] = 'yellow'
    >>> print(alien)
    {'color': 'yellow', 'points': 5}
    
  • Removing Key-Value Pairs

  • 
    >>> del alien['points']
    >>> print(alien)
    {'color': 'yellow'}
    
  • Merge two dictionaries

  • 
    >>> dict1 = { "name":"owen", "age": 18 }
    >>> dict2 = { "birthday": "1999-11-22"}
    >>> x = dict( dict1, **dict2 )
    >>> print(x)
    {'name': 'owen', 'age': 18, 'birthday': '1999-11-22'}
    
    
    >>> a = { 'x' : 1 , 'y' : 2 }
    >>> b = { 'y' : 3 , 'z' : 4 }
    >>> c = dict(a,**b)
    >>> print(c)
    {'x': 1, 'y': 3, 'z': 4}
    
  • The in operator works on dictionaries. (keys) To see whether something appears as a value in a dictionary, you can use the method .values().

  • 
    >>> x = {'one': 'apple', 'two': 'banana', 'three': 'orange'}
    >>> 'one' in x
    True
    >>> 'uno' in x
    False
    >>>'orange' in x.values()
    True
    

Methods of Dictionary


>>> stuff = {}
>>> dir(stuff)

['__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__',
 '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
 '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__ior__',
 '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__',
 '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__ror__', '__setattr__',
 '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 
 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update','values']

>>> help(dict.get)
Help on method_descriptor:

get(self, key, default=None, /)
    Return the value for key if key is in the dictionary, else default.
  • Suppose you are given a string and you want to count how many times each letter appears.
  • 
    word = 'banana'
    d = {}
    word_list = list('banana')
    for c in word_list:
        if c not in d:
            d[c] = 1
        else:
            d[c] = d[c] + 1
    print(d)
    
    
    {'b': 1, 'a': 3, 'n': 2}
    
  • Dictionaries have a method called .get() that takes a key and a default value.
  • 
    >>> counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}
    >>> print(counts.get('jan', 0)) #0 is the default value
    100
    >>> print(counts.get('anni', 1550))
    1550
    
    
    word = 'banana'
    d = {}
    word_list = list('banana')
    for c in word_list:
        d[c] = d.get(c,0) + 1
    print(d)
    

.items(), .keys(), .values()


# Looping Through All Key-Value Pairs
favorite = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    }
for x, y in favorite.items():
    print(x, y)

jen python
sarah c
edward ruby

# Looping Through All Values
favorite = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    }
for y in favorite.values():
    print(y)

python
c
ruby

# Looping Through All the Keys in a Dictionary
favorite = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    }
for x in favorite.keys():
    print(x)

jen
sarah
edward

friends = ['sarah', 'jen']
for x in favorite.keys():
    if x in friends:
        print(x+" "+favorite[x])


Jen python
Sarah c

Nesting

  • You can nest a set of dictionaries inside a list, a list of items inside a dictionary, or even a dictionary inside another dictionary. A list or a dictionary cannot be the key (The key should be immutable).

  • Dictionaries in a list

  • 
    alien_0 = {'color': 'green', 'points': 5}
    alien_1 = {'color': 'yellow', 'points': 10}
    alien_2 = {'color': 'red', 'points': 15}
    
    aliens = [alien_0, alien_1, alien_2]
    
  • A List in a Dictionary

  • 
    pizza = {
        'crust': 'thick',
        'toppings': ['mushrooms', 'extra cheese'],
        }
    print(pizza['crust'], pizza['toppings'][1])
    
    
    thick extra cheese
    
  • A Dictionary in a Dictionary


users = {
    'aeinstein': {
        'first': 'albert',
        'last': 'einstein',
        'location': 'princeton',
        },

    'mcurie': {
        'first': 'marie',
        'last': 'curie',
        'location': 'paris',
        },
    }

full_name = users['aeinstein']['first']+" "+users['aeinstein']['last']
location = users['aeinstein']['location']

print("Full name: " + full_name)
print("Location: " + location)


Full name: Albert Einstein
Location: Princeton

Dictionaries: Summary

  • Elements are key-value pairs. Empty dictionary {}

  • Features:unpredictable order, key-value pairs are mutable (keys are immutable, but you can modify values). Do not make repeated keys.

  • .get() (value or default value)

    Looping: .items(), .keys(), .values()

  • in operator works on keys (but you can use .values())

  • Nesting: A list of dictionaries, a list in a dictionary, a dictionary in a dictionary

4.2 Money Tracker v2.0

  • New Feature! Add the classification of each expense

print("简易记账本(三月)")
March=[]
for date in range(31):
    # March.append([])
    March.append({}) 

while True:
    day=int(input("请问输入几号的开销?结束请输入0:"))
    if day==0:
        break
    else:
        print("请输入每一笔开销,结束请输入0:") 
        n=1
        while True:
            each = float(input("第"+str(n)+"笔:"))
            if each == 0:
                break
            else: 
                # March[day-1].append(each)
                y = input("请选择: a.衣 b.食 c.住 d.行 e.其他")
                March[day-1][y]=March[day-1].get(y,0)+each
                n = n + 1
            print("记录成功")

total=0
for each_day in March:
    if each_day:
        # total = total + sum(each_day)
        total = total + sum(each_day.values())

print("本月支出汇总报告")
print("总支出:" + str(total))

sub = {}
items = ['a', 'b', 'c', 'd', 'e']
for each_day in March:
    for z in items:
        sub[z] = each_day.get(z,0)+sub.get(z,0)
print("衣:", sub['a']) 
print("食:", sub['b']) 
print("住:", sub['c']) 
print("行:", sub['d']) 
print("其他:", sub['e'])   

4.3 Tuples

  • A tuple is a sequence of values much like a list. The important difference is that tuples are immutable

  • The empty tuple can be written as tuple().

  • 
    >>> t = () #Empty is False
    >>> print(t)
    () 
    
    >>> t = ('a', 'b', 'c', 'd', 'e')
    
  • To create a tuple with a single element, you have to include the final comma:

  • 
    >>> t1 = ('a',)
    >>> type(t1)
    tuple
    
    >>> t2 = ('a')
    >>> type(t2)
    str
    
  • Most list operators also work on tuples.

  • 
    >>> t = ('a', 'b', 'c', 'd', 'e')
    >>> print(t[0])
    'a'
    
    >>> print(t[1:3])
    ('b', 'c')
    
  • Tuple is immutable. You can't modify the elements of a tuple, but you can replace one tuple with another:

  • 
    >>> t[0] = 'A'
    TypeError: object doesn't support item assignment
    
    >>> t = ('A',) + t[1:]
    >>> print(t)
    ('A', 'b', 'c', 'd', 'e')
    
  • If you want to modify a tuple, you can convert it to a list, and then convert it back.

  • 
    >>> t = ('a', 'b', 'c', 'd', 'e')
    >>> s = list(t) 
    >>> s[0] = 'A'
    >>> t = tuple(s) 
    

Lists and Tuples

  • Comparing and sorting Tuples (the same for lists in list)


>>> (0, 1, 2) < (0, 3, 4)
True
>>> (0, 1, 2000000) < (0, 3, 4)
True

>>> t = [(2, 4), (0, 1, 2), (0, 3, 4)]
>>> t.sort()
>>> print(t)
[(0, 1, 2), (0, 3, 4), (2, 4)]

>>> t = [('c', 3), ('a', 2), ('b', 1)]
>>> t.sort()
>>> print(t)
[('a', 2), ('b', 1), ('c', 3)]
  • Multiple Assignment (the same for lists)


>>> m = ('have', 'fun')  
>>> x, y = m  #(x, y) = m
>>> x
'have'
>>> y
'fun'
>>> x, y = y, x #swap
  • in operator (the same for lists)


>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print('a' in t) 
True
  • Iteration with multiple values (the same for list of lists, tuple of lists)


t = [('a',1), ('b',2), ('c',3)]
for x, y in t:
    print(x)
    print(y)
# for x in t?

Dictionaries and tuples


>>> d = {'a':10, 'b':1, 'c':22}
>>> t = list(d.items())
>>> t
[('b', 1), ('a', 10), ('c', 22)]
  • Using tuples as keys in dictionaries


>>> directory = dict()
>>> directory[('Taylor', 'Swift')] = 100
>>> print(directory)

{('Taylor', 'Swift'): 100}

Tuples: Summary

  • The element can be any type. The empty is ().

  • Features: Ordered, Immutable, Repeatable

  • Index and slice are the same with that of lists.

  • You cannot modify the elements of a tuple, but you can replace one tuple with another.

  • Comparing, multiple assignment, in operator

  • Tuples can be keys of a dictionary.

4.4 List, dictionary, tuple

Comparison

container Feature
List [] ordered; mutable; repeatable
Tuple () ordered; immutable; repeatable
Dictionary {} not ordered; key-value pairs and values are mutable, keys are not; values are repeatable, keys are not

Mutable and Immutable (可变和不可变)

  • Values are immutable. Thus, numbers, strings, tuples are immutable. Lists, dictionaries are mutable.

  • What does it mean for immutable or mutable? Assignment, Modification, Reference

  • 1. what is assignment? variable $\rightarrow$ computer memory $\rightarrow$ object

2. Modification

  • When you want to modify the immutable object, you can only assign a new object. It changes the address in the memory.
  • 
    >>> x = "abc"
    >>> x = "def"
    
  • There are two ways for you to modify the mutable object. a. make a new assignment; b. make a modification by methods for lists or some ways for dictionaries.
  • a. make a new assignment

    
    >>> x = [1,2,3]
    >>> x = [4,5,6]
    

b. make a modification by methods for lists. You do not change the address.


>>> x = [1,2,3]
>>> del x[2]
>>> del x[1]
>>> del x[0]
>>> x.append(4)
>>> x.append(5)
>>> x.append(6)

3. Reference


>>> x = "abc"
>>> y = x
>>> x = "def"
>>> print(y)
"abc"

>>> x = [1,2,3]
>>> y = x
>>> del x[2]
>>> x.append(4)
>>> print(y)
[1,2,4]

>>> x = [1,2,3]
>>> y = x[:] 
>>> del x[2]
>>> x.append(4)
>>> print(y)
[1,2,3]

Summary

  • Dictionaries, Tuples
  • Reading: Python for Everybody
    • Chapter 9, 10.1-10.5, 10.7-10.8