Konrad
Konrad

Reputation: 902

str.format() with nested dictionary

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.

Upvotes: 12

Views: 5499

Answers (1)

sacuL
sacuL

Reputation: 51425

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'

Upvotes: 26

Related Questions