Home > OS >  KeyError: 'count' when using str.format() with a dict (Google example not working)
KeyError: 'count' when using str.format() with a dict (Google example not working)

Time:01-13

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?

CodePudding user response:

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'

CodePudding user response:

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)
  • Related