Skip to content Skip to sidebar Skip to footer

How To Print Newlines In A Dictionary?

I am attempting to create a query through a dictionary that looks something like this: Name:name ID:id Date of Birth:dob The second name is a preset value that the user typed in

Solution 1:

It looks like you're trying to print a dictionary and somehow have it automatically know what formatting you're after. Instead, be explicit about the formatting you require.

Let's start with some sample data:

d = {
    'name': 'bob',
    'dob': 'old',
    'ID': 1
}

Since you're preceding two of the fields with a newline, then I'll take a stab that actually you want the key/value on separate lines in a certain order (ID being first). So, let's set up a format string:

layout = """
    ID: {ID}
    Name: {name}
    Date of Birth: {dob}
"""

We're using a multi-line string here ''' - so that we can build a template like text across multiple lines maintaining readability.

Finally, we use the layout and pass our dictionary to it, and Python will substitute {name} with the value in the dictionary with the key name (and so on...)

print layout.format(**d)

Result:

ID:1Name: bob
Dateof Birth: old

Post a Comment for "How To Print Newlines In A Dictionary?"