Home > Software engineering >  python changing a list into a dictionary
python changing a list into a dictionary

Time:12-04

so i'm taking a python class right now and am struggling with dictionaries at the moment. my assignment is simple, i have to create a fucntion "letter_positions" which will return a dictionary of all positions of a letter in a string.

for example

positions = letter_positions("fifteen e's, seven f's, four g's, six h's, eight i's, four n's, five o's, six r's, eighteen s's, eight t's, four u's, three v's, two w's, three x's")

positions['e']

should return

{4, 5, 8, 14, 16, 43, 67, 83, 88, 89, 97, 121, 122, 141, 142}

so i'm pretty much done with the assignment but i'm running into the issue that i have all values (positions) assigned to the keys (letters) as a list.

here's my code:

def letter_positions(n):
    answer = {}
    n = n.lower()
    x = 0
    for letter in n:
        if letter.isalpha():
            if letter not in answer:
                answer[letter] = []
            answer[letter].append(x)
        x  = 1
    return answer

so instead of getting a dictionary of positions i'm getting a list of positions.

positions = letter_positions("fifteen e's, seven f's, four g's, six h's, eight i's, four n's, five o's, six r's, eighteen s's, eight t's, four u's, three v's, two w's, three x's")

positions['e']

returns


[4, 5, 8, 14, 16, 43, 67, 83, 88, 89, 97, 121, 122, 141, 142]

is there any way for me to simply change the list into a dictionary or am i approaching this in a completely wrong way?

CodePudding user response:

If I understand your question correctly, you would like to return a dictionary with the searching key (letter).

One way to achieve that in more Pythonic way is to use collections defaultdict factory method to build the indices as list:

from collections import defaultdict

def letter_index(sentence):
    answer = defaultdict(list)
    
    for idx, ch in enumerate(sentence):
        answer[ch].append(idx)
        
    return answer
    
positions = letter_index("fifteen e's, seven f's, four g's, six h's, eight i's, four n's, five o's, six r's, eighteen s's, eight t's, four u's, three v's, two w's, three x's")

ch = 'e'

for k, v in positions.items():
    if k == ch:
        print(k, v)

# e [4, 5, 8, 14, 16, 43, 67, 83, 88, 89, 97, 121, 122, 141, 142]

CodePudding user response:

change your code like this

def letter_positions(n):
    answer = {}
    n = n.lower()
    x = 0
    for letter in n:
        if letter.isalpha():
            answer[letter] = answer.get(letter,[])#if there is not the key letter add it as key with value an empty list
            answer[letter].append(x)
        x=x 1
    return answer
positions = letter_positions("fifteen e's, seven f's, four g's, six h's, eight i's, four n's, five o's, six r's, eighteen s's, eight t's, four u's, three v's, two w's, three x's")
print(positions['e'])
  • Related