[SOLVED] How to convert list to dictionary using alpha as key and digit as values

Issue

I have a list like this:

['aa', 3, 6, 7, 1, 5, 1, 8, 7, 'ab', 3, 2, 9, 'ac', 9, 2, 5, 8]

I’d like to write a function to output the length of the digits following by the character:

key['aa'] = 8 because aa is followed by 3, 6, 7, 1, 5, 1, 8, 7
or key['ab'] = 3 since 3 digits followed by 'ab'.

I tried to use for loop and if-else statement to convert the list to dictionary first, but I failed miserably. Now I totally have no clue to work this out.I tried:

def listToDict(lst):
  dictOfWords = {lst[i] : lst[i+1] 
             for i in range(0, len(lst)) 
             if lst[i+1].isdigit():lst[i+1]=lst[i+1].append(lst[i+1]) )}
 return dictOfWords

Because I cannot calculate the length if the data type is involved.

I would really appreciate if anyone can help?

Solution

You can use isinstance to check if item is a string and the count the number of occurrences of non-string items in else condition.

data = ['aa', 3, 6, 7, 1, 5, 1, 8, 7, 'ab', 3, 2, 9, 'ac', 9, 2, 5, 8]
count = 0
result = {}
current = None
for item in data:
    if isinstance(item, str):
        if current:
            result[current] = count
        count = 0
        current = item
    else:
        count += 1
result[current] = count
print(result)

Answered By – Albin Paul

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *