Search code examples
pythonpython-3.xetl

Create Dictionary With Position of Character and its Respective Count


I have multiple strings like:

0000NNN
000ANNN

I wish to get a dictionary which has the position of the character in each string as the key and the count of its respective 0 as the value (If the character is NOT 0, it can be ignored). So for the above strings, the output would be:

1:2
2:2
3:2
4:1
5:0
6:0
7:0

So far i tried this:

ctr=1
my_dict={}
for word in string_list:
    for letter in word:
        if letter == "0":
            if ctr not in my_dict.keys():
                my_dict[ctr]=1
            else:
                my_dict[ctr]+=1
        else:
            pass        
print(my_dict)  

What am I doing wrong as the output is not correct?


Solution

  • Looks like you never increases and resetting ctr and not adding my_dict[ctr]=0 for 5,6,7. Something like this should work:

    string_list = ['0000NNN','000ANNN']
    
    my_dict={}
    for word in string_list:
        ctr=1 #Moved
        for letter in word:
            if letter == "0":
                if ctr not in my_dict.keys():
                    my_dict[ctr]=1
                else:
                    my_dict[ctr]+=1
            else:
                my_dict[ctr]=0 #Added
            ctr+=1 #Added
    print(my_dict)  #{1: 2, 2: 2, 3: 2, 4: 0, 5: 0, 6: 0, 7: 0}