'Appending values to a tuple
This code appends a new value directly to a tuple. But, tuples are supposed to be nonchangeable. Could someone explain what is happening here?
word_frequency = [('hello', 1), ('my', 1), ('name', 2),
('is', 1), ('what', 1), ('?', 1)]
def frequency_to_words(word_frequency):
frequency2words = {}
for word, frequency in word_frequency:
if frequency in frequency2words:
frequency2words[frequency].append(word)
else:
frequency2words[frequency] = [word]
return frequency2words
print(frequency_to_words(word_frequency))
Result: {1: ['hello', 'my', 'is', 'what', '?'], 2: ['name']}
Solution 1:[1]
The .append() operation is done on the list values in the frequency2words dictionary, not the tuples in word_frequency.
You can rewrite your code to be more concise using .setdefault(), which should also make it more clear what you're appending to.
def frequency_to_words(word_frequency):
frequency2words = {}
for word, frequency in word_frequency:
frequency2words.setdefault(frequency, []).append(word)
return frequency2words
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BrokenBenchmark |
