user1330225
user1330225

Reputation: 177

Append to List Nested in Dictionary

I am trying to append to lists nested in a dictionary so I can see which letters follow a letter. I have the desired result at the bottom I would like to get. Why is this not matching up?

word = 'google'
word_map = {}

word_length = len(word)
last_letter = word_length - 1

for index, letter in enumerate(word):
    if index < last_letter:
        if letter not in word_map.keys():
            word_map[letter] = list(word[index+1])
        if letter in word_map.keys():
            word_map[letter].append(word[index+1])
    if index == last_letter:
        word_map[letter] = None

print word_map

desired_result = {'g':['o', 'l'], 'o':['o', 'g'], 'l':['e'],'e':None}
print desired_result

Upvotes: 0

Views: 224

Answers (2)

mgilson
mgilson

Reputation: 309929

Use the standard library to your advantage:

from itertools import izip_longest
from collections import defaultdict

s = 'google'

d = defaultdict(list)
for l1,l2 in izip_longest(s,s[1:],fillvalue=None):
    d[l1].append(l2)

print d

The first trick here is to yield the letters pair-wise (with a None at the end). That's exactly what we do with izip_longest(s,s[1:],fillvalue=None). From there, it's a simple matter of appending the second letter to the dictionary list which corresponds to the first character. The defaultdict allows us to avoid all sorts of tests to check if the key is in the dict or not.

Upvotes: 5

Pavel Anossov
Pavel Anossov

Reputation: 62908

if letter not in word_map.keys():
   word_map[letter] = list(word[index+1])

# now letter IS in word_map, so this also executes:
if letter in word_map.keys():
    word_map[letter].append(word[index+1])

You meant:

if letter not in word_map.keys():
   word_map[letter] = list(word[index+1])

else:
   word_map[letter].append(word[index+1])

Another thing: what if the last letter also occurs in the middle of the word?

Upvotes: 1

Related Questions