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.
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.
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.
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'}.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With