Reputation: 11
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 through raw_input. Same for the id
and the dob
.
Here is what my current code looks like:
students[id] = {
"\nName":name,
"\nDate of Birth":dob,
"ID":id,
}
And here's how it turns out:
{'\nName': 'Sample Name', '\nDate of Birth': 'Sample Birthdate', 'ID': 'Sample ID'}
I know you need to have /print before a string for the newline to work properly, but I'm not able to use that within the dictionary. Is there a way to bypass this?
Upvotes: 1
Views: 1126
Reputation: 142256
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: 1
Name: bob
Date of Birth: old
Upvotes: 6