Reputation: 396
I want to loop through content of a file, compute the key of each word and then store the words with same key in a list.
In python, it's like below:
dictionary = {}
for word in file:
key = dosomecalucation(word)
dictionary.setdefault(key, [])
dictionary[key].append(word)
In R, how can I declare a dictionary with key as string and value as a list? How can I check whether a key exist in the dictionary?
Upvotes: 0
Views: 1751
Reputation: 26
You could use the hash
package for this task:
library(hash)
h <- hash()
for (word in file) {
key <- dosomecalculation(word)
if (!has.key(key, h)) {
h[key] <- list()
} else {
h[key] <- append(h[[key]], word)
}
}
Using [[
for indexing (e.g. h[["foo"]]
) will then return the corresponding list.
Upvotes: 1