1

I am jumping into Python using https://developers.google.com/edu/python/dict-files. It's all been pretty intuitive so far from a C/C++/C# background, but I'm getting an error when using an example of printing elements from a dict. Putting the following into the CL interpreter is no problem:

h = {}
h['word'] = 'garfield'
h['count'] = 42
s = 'I want %(count)d copies of %(word)s' % h  # %d for int, %s for string
# 'I want 42 copies of garfield'

# You can also use str.format().
s = 'I want {count:d} copies of {word}'.format(h)

... up until the last line s = 'I want {count:d} copies of {word}'.format(h)

which is giving me KeyError: 'count' The code is verbatim from the example in the linked page.

I have Python 3.11.1 on win32. Maybe the tutorial is old, or do I need to import another module, or what?

cottontail
  • 10,268
  • 18
  • 50
  • 51
JSteh
  • 165
  • 1
  • 8

2 Answers2

3

I think you're mixing two things: formatted string literals (f-strings); and the string format() method.

Examples of both:

h = {}
h['word'] = 'garfield'
h['count'] = 42
s = 'I want %(count)d copies of %(word)s' % h

# at this point s contains "I want 42 copies of garfield"
print(s)

# use formatted string literals (f-strings)
s = f'I want {h["count"]} copies of {h["word"]}'  
print(s)

# use the string .format() method
s = 'I want {} copies of {}'.format(h["count"], h["word"]) 
print(s)
codingatty
  • 2,026
  • 1
  • 23
  • 32
  • I'm accepting this as the answer. I hadn't looked much into the format() method, but this makes sense and works in the interpreter. I still find it strange that the tutorial I'm using has broken code :/ . Live and learn I guess. Is it possible that this code ran on older versions of Python? I have noticed that their examples have broken `print "some string"` rather than the correct `print("some string")`. That appears to be a syntax element that changed. – JSteh Jan 13 '23 at 13:57
  • In between Python 2 and 3, print changed from a statement ('print "some string"') on Python 2 to a method ('print("some string")') in Python 3, You may be looking at a tutorial written for Python 2. – codingatty Jan 14 '23 at 18:31
2

You need to unpack the dictionary (using **) inside .format. The idea is to unpack the dictionary into individual arguments:

s = 'I want {count:d} copies of {word}'.format(**h)
# 'I want 42 copies of garfield'
cottontail
  • 10,268
  • 18
  • 50
  • 51