2

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?

3
  • Can you post your dictionary? As well as full code? Commented Aug 5, 2016 at 17:05
  • if possible, please post your sample code Commented Aug 5, 2016 at 17:05
  • the values are read from a pickled file, which the other guy unpickled first. Ι know it's not much of a help, but this is all I've got... It's pretty poorly written code... Commented Aug 5, 2016 at 17:06

4 Answers 4

1

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']
Sign up to request clarification or add additional context in comments.

Comments

0

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))

1 Comment

You could convert this to a list comprehension if you want to [print("n/a") if value == "" else print(str(value)) for value in dict.values()]
0

Try using

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

1 Comment

are you sure it work? are you saying [k for k in ['','1'] if k else "n/a"] will work?
0

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.