Reputation: 785
I want to create a default dict by using a string. Let's say I have the word 'hello': I would like the function to return:
{'h':{'e'}, 'e':{'l'}, 'l':{'l', 'o'}}
I tried creating a defaultdict(set) first in order to get rid of all the duplicates, but I'm not sure how to obtain the key's value from the next letter in the string (if that makes sense?)
def next(s):
x = defaultdict(set)
for i in range(len(s)-1):
x[i].add(s[i+1]) #this is the part i am unsure about
return x
This returns me an error saying how the str object has no attribute to 'add'.
Upvotes: 0
Views: 2458
Reputation: 1123520
Your code works just fine:
>>> from collections import defaultdict
>>> def next(s):
... x = defaultdict(set)
... for i in range(len(s)-1):
... x[i].add(s[i+1])
... return x
...
>>> next('hello')
defaultdict(<type 'set'>, {0: set(['e']), 1: set(['l']), 2: set(['l']), 3: set(['o'])})
Perhaps your running code uses defaultdict(str)
by accident?
You want to use s[i]
as the key though:
def next(s):
x = defaultdict(set)
for i in range(len(s)-1):
x[s[i]].add(s[i+1])
return x
This produces the desired output:
>>> def next(s):
... x = defaultdict(set)
... for i in range(len(s)-1):
... x[s[i]].add(s[i+1])
... return x
...
>>> next('hello')
defaultdict(<type 'set'>, {'h': set(['e']), 'e': set(['l']), 'l': set(['l', 'o'])})
You can also loop over the string as an iterator, 'remembering' the previous character:
def next_dict(s):
x = defaultdict(set)
prev = s[0]
for char in s[1:]:
x[prev].add(char)
prev = char
return x
It is much easier to track the previous value(s), looking behind, than it is to look ahead; you already passed over the previous values, after all.
Upvotes: 2