Home > Mobile >  How to convert list to dictionary using alpha as key and digit as values
How to convert list to dictionary using alpha as key and digit as values

Time:01-30

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?

CodePudding user response:

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)

CodePudding user response:

You can just iterate the list checking types of items and put the items into resulting dict when it's needed:

in_list = ['aa', 3, 6, 7, 1, 5, 1, 8, 7, 'ab', 3, 2, 9, 'ac', 9, 2, 5, 8]
d = {}
c_item = None
c_count = 0

for item in in_list:
    if type(item) is str:
        if c_item:
            d[c_item] = c_count

        c_item = item
        c_count = 0
    if type(item) is int:
        c_count  = 1

if c_item is not None:
    d[c_item] = c_count

print(d)

Output:

{'aa': 8, 'ab': 3, 'ac': 4}

CodePudding user response:

Thought I'd have a bit of fun with this one and make it work using itertools.groupby

from itertools import groupby

def grouper():
    current = None
    def check(value):
        nonlocal current

        if isinstance(value, str):
            current = value

        return current
            
    return check


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


result = {k:len(list(grp)) - 1 for k, grp in groupby(lst, key=grouper())}
print(result)

Which gives

{'aa': 8, 'ab': 3, 'ac': 4}

CodePudding user response:

Here's a another take on it that uses unpacking, zip, and itertools.pairwise:

import itertools

my_list = ["aa", 3, 6, 7, 1, 5, 1, 8, 7, "ab", 3, 2, 9, "ac", 9, 2, 5, 8]

idx, alpha = zip(*[(i, x) for i, x in enumerate(my_list) if isinstance(x, str)])
idx = *idx, len(my_list)

key = {a: j - i - 1 for a, (i, j) in zip(alpha, itertools.pairwise(idx))}

Output:

>>> key
{'aa': 8, 'ab': 3, 'ac': 4}

CodePudding user response:

l=[x for x in input("Enter the list:").split()]
dictl={}
lenl=len(l)
ll=[]
for i in l:
    if i.isdigit():
        ll.append(int(i))
    else:
        ll.append(i)
i=0
while i<lenl:
    if isinstance(ll[i],str):
        strc=ll[i]
        c=0
        i =1
        while i<lenl and isinstance(ll[i], int):
            c =1
            i =1
        dictl[strc]=c
print(dictl)
  •  Tags:  
  • Related