Jack
Jack

Reputation: 722

Replace dictionary's empty values python

First of all, I'm modifying another guy's code.

I'm trying to print the values of dictionary that correspond to a key like so:

print (map(str, dict[key]))

All works fine, but there are some fields that are printed with just the double quotes, like so ['some_value', '', 'other_value', etc...], what I'm trying to accomplish here, is to replace the single quotes '', with n/a

my approach, at first, was to do this: print (map(str.replace("\'\'", "n/a"), dict[key])), but I get the TypeError message: TypeError: replace() takes at least 2 arguments (1 given)

How can I work around this?

Upvotes: 2

Views: 2722

Answers (4)

Andrea
Andrea

Reputation: 603

You could solve your problem in a more simple way without using map(). Just use list() than you can loop on every single character of your string (diz[key]) and then replace the empty space with the 'n/a' string as you wish.

diz[key] = 'a val'
[w.replace(' ', 'n/a') for w in list(diz[key])]
>> ['a', 'n/a', 'v', 'a', 'l']

Upvotes: 0

galaxyan
galaxyan

Reputation: 6151

map function needs func and iterable

data = { '':'',1:'a'}
print (map( lambda x: x if x else 'n/a', data.values()))
['n/a', 'a']

for value as list:

data = { 'a' :[1,'',2]}
print (map( lambda x: str(x) if x else 'n/a', data['a']))
['1', 'n/a', '2']

Upvotes: 1

Asish M.
Asish M.

Reputation: 2647

Try using

print([k if k else "n/a" for k in map(str, dict[key])])

Upvotes: 0

Camsbury
Camsbury

Reputation: 121

You should probably just expand to a for loop and write:

for value in dict.values():
    if value == "":
        print("n/a")
    else:
        print(str(value))

Upvotes: 0

Related Questions