tp07-dictionaries
tp07-dictionaries
António J. R. Neves
João Rodrigues
• Dictionaries
Dictionaries
Data Types
Simple types
(bool, int, float, complex)
Sequences:
(list, tuple, str)
Sets: Mappings:
(set, frozenset) Dictionaries (dict)
Dictionaries
• Use pop(key) to remove the item with the given key and
return its value.
d = {10:'dez', 20:'vinte', 1000:'mil'}
Play ▶
x = d.pop(10) #-> x == 'dez'
print(d) # {20:'vinte', 1000: 'mil'}
• Suppose you are given a string and you want to count how
many times each letter appears there:
message = 'parrot'
d = dict()
for c in message:
if c not in d:
d[c] = 1
else:
d[c] += 1 Play ▶
#A #B
d = {} d = {}
for c in message: for c in message:
if c not in d: if c not in d:
d[c] = 1 d[c] = 0
else: d[c] += 1
d[c] += 1
#C #D
d = {} d = {}
for c in message: for c in message:
d[c] = d.get(c, 0) + 1 d.setdefault(c, 0)
d[c] += 1
Dictionaries: updating (2)
#A #B
d = {} d = {}
for w in wordlist: for w in wordlist:
k = len(w) k = len(w)
if k not in d: if k not in d:
d[k] = [w] d[k] = []
else: d[k].append(w)
d[k].append(w)
#C #D
d = {} d = {}
for w in wordlist: for w in wordlist:
k = len(w) k = len(w)
d[k] = d.get(k, []) d.setdefault(k, []).append(w)
Play ▶
d[k].append(w)
wordlist=['to','be','or','not','to','be','that','is','the','question']
#A, B, C or D...
d -> {2: ['to', 'be', 'or', 'to', 'be', 'is'], 3: ['not', 'the'],
4: ['that'], 8: ['question']}
Dictionaries and lists of tuples