idlatva
idlatva

Reputation: 29

Remove spaces from value in a dictionary

def f(a):
    for item in a:
        c = item
        b = len(a[item])
        print('{} {}'.format(c,b))

I want to create a function f in python where you can print all keys and lengths of the keys' associated values ​​in a dictionary, for example a={'A': 'hey you', 'B': 'hello'} should give us the output:

A 6
B 5

But with my code I get the output:

A 7
B 5

Because it count spaces in len(), how can I fix this? This is what I have tried so far but it gives me TypeError: string indices must be integers

def f(a):
    for item in a:
        c = item
        b = a[item]
        for i in b:
            if b[i] == ' ':
                return b.strip()
            else:
                return b
    print('{} {}'.format(c,len(b)))

Upvotes: 0

Views: 64

Answers (3)

balderman
balderman

Reputation: 23815

Something like this (Note that we do not create a new string)

a = {'A': 'hey you   ', 'B': 'hello'}
for k, v in a.items():
    print(f'{k} --> {len(v) - v.count(" ")}')

output

A --> 6
B --> 5

Upvotes: 2

user2390182
user2390182

Reputation: 73470

It is unnecessary to create a new string to count the non-space chars. You can do so directly:

def ns_len(s):
    return sum(c != " " for c in s)  # count all non-" "
    # return sum(map(" ".__ne__, s))

def f(a):
    for k, v in a.items():
        print(f'{k} {ns_len(v)}')

>>> f(a)
A 6
B 5

Upvotes: 2

user15801675
user15801675

Reputation:

In that case, use .replace()method to replace all the white spaces.:

len(a[item].replace(" ",''))
def f(a):
    for item in a:
        c = item
        b = len(a[item].replace(" ",''))
        print('{} {}'.format(c,b))

Upvotes: 1

Related Questions