2

Suppose I have the following dictionary.

params = {'a': 'aaa', 'b': 'bbb', 'c': 'ccc', 'd': 'ddd-hoge'}

When printing using the following script,

>>> print("1: {a} 2: {b} 3: {c} 4: {d}.split('-')[0]".format(**params))

the output will be

"1: aaa 2: bbb 3: ccc 4: ddd-hoge.split('-')[0]"

How should I modify the script to get the same output as the following?

"1:aaa 2:bbb 3:ccc 4:ddd"
2
  • 1
    What happens when you move the closing curly brace to after [0]? Commented Jun 1, 2018 at 3:49
  • 1
    AttributeError: 'str' object has no attribute 'split('-')' is thrown Commented Jun 1, 2018 at 3:51

3 Answers 3

2

This seems to work:

params = {'a': 'aaa', 'b': 'bbb', 'c': 'ccc', 'd': 'ddd-hoge'}

print("1: {a} 2: {b} 3: {c} 4: {d}".format(**{
    k: v.split('-')[0] for k, v in params.items()}))

This does the processing on the dict, and then formats for print.

Results:

1: aaa 2: bbb 3: ccc 4: ddd
Sign up to request clarification or add additional context in comments.

Comments

1

Just simply split afterward:

print("1: {a} 2: {b} 3: {c} 4: {d}".format(**params).split('-')[0])

1 Comment

It does work in this extremely limited example, but it's a terrible solution. Anything following the first dash is removed, regardless where that dash happens to be.
0

An operation of that complexity won't be handled by the formatting mini language. You would have to do the transformation externally.

One way would be to make a copy of the dictionary and update the particular value you want:

p = params.copy()
p['d'] = params['d'].split('-')[0]
print("1: {a} 2: {b} 3: {c} 4: {d}".format(**p))

You could of course modify params in place as well. A more elegant solution might be to apply the transformation to all the values:

print("1: {a} 2: {b} 3: {c} 4: {d}".format(**{k: v.split('-')[0] for k, v in params.items()}))

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.