03 Python
03 Python
1
Updating Dictionaries Removing dictionary entries
>>> d = {‘user’:‘bozo’, ‘pswd’:1234} >>> d = {‘user’:‘bozo’, ‘p’:1234, ‘i’:34}
>>> d[‘user’] = ‘clown’ >>> del d[‘user’] # Remove one.
>>> d >>> d
{‘user’:‘clown’, ‘pswd’:1234}
{‘p’:1234, ‘i’:34}
• Keys must be unique
>>> d.clear() # Remove all.
• Assigning to an existing key replaces its value
>>> d
>>> d[‘id’] = 45
>>> d {}
{‘user’:‘clown’, ‘id’:45, ‘pswd’:1234}
>>> a=[1,2]
• Dictionaries are unordered
>>> del a[1] # del works on lists, too
• New entries can appear anywhere in output >>> a
• Dictionaries work by hashing [1]
2
Dictionary example: wf1.py Dictionary example wf1.py
#!/usr/bin/python #!/usr/bin/python
import sys import sys
freq = {} # frequency of words in text freq = {} # frequency of words in text
for line in sys.stdin: for line in sys.stdin:
This is a common
for word in line.split(): for word in line.split(): pattern
if word in freq: if word in freq:
freq[word] = 1 + freq[word] freq[word] = 1 + freq[word]
else: else:
freq[word] = 1 freq[word] = 1
print freq print freq
3
Dictionary example wf4.py Dictionary example wf4.py
#!/usr/bin/python for line in sys.stdin:
import sys for word in line.split():
punctuation = """'!"#$%&\'()*+,-./:;<=>? word = word.strip(punct).lower()
@[\\]^_`{|}~'""" if word not in stop_words:
freq[word] = freq.get(word,0)+1
freq = {} # frequency of words in text
4
Why must keys be immutable? defaultdict
• The keys used in a dictionary must be >>> from collections import defaultdict!
>>> kids = defaultdict(list, {'alice': ['mary',
immutable objects? 'nick'], 'bob': ['oscar', 'peggy']})!
>>> name1, name2 = 'john', ['bob', 'marley'] >>> kids['bob']!
>>> fav = name2 ['oscar', 'peggy']!
>>> d = {name1: 'alive', name2: 'dead'} >>> kids['carol']!
Traceback (most recent call last): []!
File "<stdin>", line 1, in <module> >>> age = defaultdict(int)!
TypeError: list objects are unhashable >>> age['alice'] = 30!
• Why is this? >>> age['bob']!
0!
• Suppose we could index a value for name2 >>> age['bob'] += 1!
• and then did fav[0] = “Bobby” >>> age!
defaultdict(<type 'int'>, {'bob': 1, 'alice': 30})!
• Could we find d[name2] or d[fav] or …?
!
!