Reputation: 12870
I'm trying to get a value from a dictionary with string interpolation.
The dictionary has some digits, and a list of digits:
d = { "year" : 2010, \
"scenario" : 2, \
"region" : 5, \
"break_points" : [1,2,3,4,5] }
Is it possible to reference the list in a string interpolation, or do I need to identify unique keys for each?
Here's what I've tried:
str = "Year = %(year)d, \
Scenario = %(scenario)d, \
Region = %(region)d, \
Break One = %(break_points.0)d..." % d
I've also tried %(break_points[0])d
, and %(break_points{'0'})d
Is this possible to do, or do I need to give them keys and save them as integers in the dictionary?
Upvotes: 0
Views: 871
Reputation: 62948
This is possible with new-style formatting:
print "{0[break_points][0]:d}".format(d)
or
print "{break_points[0]:d}".format(**d)
The string on which this method is called can contain literal text or replacement fields delimited by braces
{}
. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument.
The field_name itself begins with an
arg_name
that is either a number or a keyword. If it’s a number, it refers to a positional argument, and if it’s a keyword, it refers to a named keyword argument....
The arg_name can be followed by any number of index or attribute expressions. An expression of the form
'.name'
selects the named attribute usinggetattr()
, while an expression of the form'[index]'
does an index lookup using__getitem__()
.
Upvotes: 4