python - Creating keys/values from a string by defaultdict -


i want create default dict using string. let's have word 'hello': function return:

{'h':{'e'}, 'e':{'l'}, 'l':{'l', 'o'}} 

i tried creating defaultdict(set) first in order rid of duplicates, i'm not sure how obtain key's value next letter in string (if makes sense?)

def next(s):     x = defaultdict(set)     in range(len(s)-1):         x[i].add(s[i+1]) #this part unsure     return x 

this returns me error saying how str object has no attribute 'add'.

your code works fine:

>>> collections import defaultdict >>> def next(s): ...     x = defaultdict(set) ...     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 running code uses defaultdict(str) accident?

you want use s[i] key though:

def next(s):     x = defaultdict(set)     in range(len(s)-1):         x[s[i]].add(s[i+1])     return x 

this produces desired output:

>>> def next(s): ...     x = defaultdict(set) ...     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 loop on string iterator, 'remembering' previous character:

def next_dict(s):     x = defaultdict(set)     prev = s[0]     char in s[1:]:         x[prev].add(char)         prev = char     return x 

it easier track previous value(s), looking behind, ahead; passed on previous values, after all.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -