13

I want to use the str.format() method like this:

my_str = "Username: {username}, User data: {user_data.attribute}".format(**items)

And apply it to items as shown below:

items = {
    "username" : "Peter",
    "user_data" : {
         "attribute" : "foo"
    }}

Is this feasible, and if so, then how? If not, I'm interested in your recommended approach.

5
  • 1
    (you don't need to have Python in the title, the tag python automatically append "python" to the title) Commented Mar 2, 2018 at 13:48
  • 1
    @user202729 It does append the first tag to the title of the webpage (<TITLE> here </TITLE>) but doesn't append it the title of the question Commented Mar 2, 2018 at 13:50
  • 2
    Exact dupe. Commented Mar 2, 2018 at 13:50
  • @Psytho But still, it's not encouraged to tag in the title. Meta post. Commented Mar 2, 2018 at 13:50
  • ... votes are weird. Sometimes dupes are downvoted and sometimes they are upvoted. Commented Mar 2, 2018 at 13:53

1 Answer 1

27

Try it like this:

items = {'username': 'Peter', 'user_data': {'attribute': 'foo'}}

my_str = "Username: {username}, User data: {user_data[attribute]}".format(**items)

>>> my_str
'Username: Peter, User data: foo'
Sign up to request clarification or add additional context in comments.

2 Comments

Huh. That works. I didn't expect it to be that easy, many thanks! I hope the question will be helpful to somebody else.
@Konrad It was =)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.