user2586260
user2586260

Reputation: 19

Using String Formatting to pull data from a dictionary

How do I use string formatting to call information from a dictionary?

Here's what I attempted so far (probably quite bad...)

value = raw_input("Indicate a number: ")
print number_stats["chm%"] % (value,)

The dictionary number_stats holds information about values "chm1", "chm2", etc.

I get a key error, which confuses me because the item chm1 is definitely stored in my dictionary.

Is there a better way to do this?

Upvotes: 0

Views: 89

Answers (4)

joente
joente

Reputation: 856

As an alternative you could use the string format method...

value = input("Indicate a number: ")
print number_stats["chm{}".format(value)]

Upvotes: 0

astrognocci
astrognocci

Reputation: 1085

print number_stats["chm%s" % (value)]

should work.

But you should do this instead:

print number_stats.get("chm%s" % (value), "some_default_value")

To avoid crashing if the user enters an invalid key. See this for more info on the get method.

Upvotes: 1

Ansuman Bebarta
Ansuman Bebarta

Reputation: 7266

Use like this. You have to use string formatting inside square brackets

>>> number_stats={'a1': 1}
>>>
>>> print number_stats['a%s' % 1]
1
>>>

Upvotes: 2

BrenBarn
BrenBarn

Reputation: 251598

When you do number_stats["chm%"] % (value,), you are doing number_stats["chm%"] first and then applying % (value,) to the result. What you want is to apply the % directly to the string:

number_stats["chm%s" % (value,)]

Note that you need %s; % by itself is not a valid string substitution.

However, there is probably a better way to do it. Why does your dictionary have keys like "chm1" and "chm2" instead of just having the numbers be the keys themselves (i.e., have keys 1 and 2)? Then you could just do number_stats[value]. (Or if you read value from raw_input you'd need number_stats[int(value)]

Upvotes: 2

Related Questions