str.format() with nested dictionary
Asked Answered
F

1

11

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.

Fanniefannin answered 2/3, 2018 at 13:46 Comment(6)
(you don't need to have Python in the title, the tag python automatically append "python" to the title)Tenaculum
@Tenaculum It does append the first tag to the title of the webpage (<TITLE> here </TITLE>) but doesn't append it the title of the questionBraun
Exact dupe.Tenaculum
@Braun But still, it's not encouraged to tag in the title. Meta post.Tenaculum
... votes are weird. Sometimes dupes are downvoted and sometimes they are upvoted.Tenaculum
Possible duplicate of How to use string.format with nested dictWeatherwise
S
24

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'
Shoffner answered 2/3, 2018 at 13:49 Comment(2)
Huh. That works. I didn't expect it to be that easy, many thanks! I hope the question will be helpful to somebody else.Fanniefannin
@Fanniefannin It was =)Valuer

© 2022 - 2024 — McMap. All rights reserved.