Why this line is using list(counts.items()): instead of dict(counts.item()):?
Question:
Isn’t the key-value pair stored in the dict() now?
Why the code is going through a list but not the dictionary?
import string
fhand = open('romeo-full.txt')
counts = dict()
for line in fhand:
line = line.translate(str.maketrans('', '', string.punctuation))
line = line.lower()
words = line.split()
for word in words:
if word not in counts:
counts[word] = 1
else:
counts[word] += 1
# Sort the dictionary by value
lst = list()
for key, val in list(counts.items()): # <----- This is the line
lst.append((val, key))
lst.sort(reverse=True)
for key, val in lst[:10]:
print(key, val)```
Answers:
counts.items()
gives you an iterable, that consists of tuples with keys mapped to their values. Here, the packing in a list is actually not needed as that returned iterable is, as the name suggests, already iterable.
So, yes you are iterating through the dictionary, but by using the counts.items() you avoid having to call counts[key]
again and again, which would cause additional computations, while you can already have all that availab with the call to items()
.
You can’t unpack dict(counts.items())
into key, val
here, because iterating over a dict
just yields the keys rather than the keys and the values.
Isn’t the key-value pair stored in the dict() now?
Why the code is going through a list but not the dictionary?
import string
fhand = open('romeo-full.txt')
counts = dict()
for line in fhand:
line = line.translate(str.maketrans('', '', string.punctuation))
line = line.lower()
words = line.split()
for word in words:
if word not in counts:
counts[word] = 1
else:
counts[word] += 1
# Sort the dictionary by value
lst = list()
for key, val in list(counts.items()): # <----- This is the line
lst.append((val, key))
lst.sort(reverse=True)
for key, val in lst[:10]:
print(key, val)```
counts.items()
gives you an iterable, that consists of tuples with keys mapped to their values. Here, the packing in a list is actually not needed as that returned iterable is, as the name suggests, already iterable.
So, yes you are iterating through the dictionary, but by using the counts.items() you avoid having to call counts[key]
again and again, which would cause additional computations, while you can already have all that availab with the call to items()
.
You can’t unpack dict(counts.items())
into key, val
here, because iterating over a dict
just yields the keys rather than the keys and the values.