Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 682
Konrad Avatar asked Mar 02 '18 13:03

Konrad


People also ask

What is format () in Python?

The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.

How do you write nested dictionary?

To create a nested dictionary, simply pass dictionary key:value pair as keyword arguments to dict() Constructor. You can use dict() function along with the zip() function, to combine separate lists of keys and values obtained dynamically at runtime.

How do you assign a value to a nested dictionary?

Adding elements to a Nested Dictionary One way to add a dictionary in the Nested dictionary is to add values one be one, Nested_dict[dict][key] = 'value'. Another way is to add the whole dictionary in one go, Nested_dict[dict] = { 'key': 'value'}.


1 Answers

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'
like image 66
sacuL Avatar answered Sep 21 '22 00:09

sacuL