Home > OS >  How to reference a dictionary to fill variables in a string?
How to reference a dictionary to fill variables in a string?

Time:03-23

I am trying to work out how to complete a task that asks the following:

Create a string and use a method to generate a description of the new car as shown below. Print it – it should be formatted like the text below (including the line breaks).

Yesterday I bought a [Make] [Model].
  
It’s not “too” old. It was made in [year] …  

I like it, though. It’s [colour], and it has [doors] doors!

The variables (make, model, year, colour and doors) need to be populated from a dictionary.

I have programmed the dictionary to look like this:

Car = {
'Make': 'Mitsubishi',
'Model': 'Lancer',
'Year': '2002',
'Colour': 'Green',
'Doors': '4',
}

How can i fill the variables in that string of text by referencing the dictionary 'Car'?

Thank you!

CodePudding user response:

You can create a template string, and then burst the dictionary values to format it. Example.

fstr = "Yesterday I bought a {} {}.\n\nIt’s not “too” old. It was made in {} …\n\nI like it, though. It’s {}, and it has {} doors!"

Car = {
'Make': 'Mitsubishi',
'Model': 'Lancer',
'Year': '2002',
'Colour': 'Green',
'Doors': '4',
}
print(fstr.format(*Car.values()))

Gives an output like

Yesterday I bought a Mitsubishi Lancer.

It’s not “too” old. It was made in 2002 …

I like it, though. It’s Green, and it has 4 doors!

So, you can apply the format with any dictionary you want. Condition: You have to make sure the key/values are in the same order of the fillers.

CodePudding user response:

python uses f-strings for this. You can use f-strings to pass variables to your string, while still keep it readable.

output = f"Yesterday I bought a {Car['Make']} {Car['Model']}."

you use \n to represent a newline, and \ to escape any "" in the string itself:

output = f"Yesterday I bought a {Car['Make']} {Car['Model']}.\nIt’s not \“too\” old. It was made in {Car['Year']}"

extra: Pythons PEP8 style guides mention that variable names (like your dictionary) should always start with a lowercase.

Edit: Thanks to Timus for pointing out a small error. added '' around dict keys.

CodePudding user response:

Build a string with the dictionary keys as placeholders (included in curly braces), and then use .format_map() with the dictionary as argument on it:

string = '''Yesterday I bought a {Make} {Model}.
  
It’s not “too” old. It was made in {Year} …  

I like it, though. It’s {Colour}, and it has {Doors} doors!'''

Car = {
    'Make': 'Mitsubishi',
    'Model': 'Lancer',
    'Year': 2002,
    'Colour': 'Green',
    'Doors': 4,
}

print(string.format_map(Car))
  • Related