-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDictionaries.py
More file actions
69 lines (57 loc) · 1.69 KB
/
Dictionaries.py
File metadata and controls
69 lines (57 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# Is like a list, the index can be anytype
# key-value, the key map the value
# function DICT create a dictionary
ing2port = dict()
print(ing2port) # empty dictionary {}
ing2port['one'] = 'um'
print(ing2port)
ing2port = {'one': 'um', 'two': 'dois', 'three': 'três'}
# dont has order
print(ing2port['two'])
# Can be use len() and IN like in Lists and Strings
vals = list(ing2port.values())
'um' in vals
# Dictionary like a count group
# Você pode criar um dicionário, estabelecendo caracteres como chaves e conta- dores como os valores correspondentes. A primeira vez em que um caractere for lido, um novo item seria adicionado ao dicionário. Após isso, o valor de um item existente seria incrementado.
palavra = 'brontosaurus'
d = dict()
for c in palavra:
if c not in d:
d[c] = 1
else:
d[c] = d[c] + 1
print(d)
# Method get(key,value)
word = 'brontosaurus'
d = dict()
for c in palavra:
d[c] = d.get(c, 0) + 1
print(d)
# Dictionary and File
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
counts = dict()
for line in fhand:
words = line.split()
for word in words:
if word not in counts:
counts[word] = 1
else:
counts[word] += 1
print(counts)
# Loops and Dictionaries
conta = {'chuck': 1, 'annie': 42, 'jan': 100}
for chave in conta:
print(chave, conta[chave])
a = {'chuck': 1, 'annie': 42, 'jan': 100}
lst = list(counts.keys()) # listas de chaves
print(lst)
lst.sort()
for key in lst:
print(key, counts[key])
# What is the purpose of the second parameter of the get() method for Python dictionaries?
# To provide a default value if the key is not found