1

I get the error "Key error:'name' "

Can anyone tell what the problem is with the following code:

import random

def mongoCountry(countryNum, provinceNum):
    """generate some test data"""
    f = open("F:\\univData\\country-mongo.json", mode = 'w')
    text = ""
    for c_n in range(0, countryNum):
        for p_n in range(0, provinceNum):
            text += "{name:country{0},provinces:[{$ref : Province,$id :   province{1}}]}\n".format(c_n, p_n)
    f.write(text)
    f.close()

mongoCountry(2, 10)

I googled it so I know it's about dict() object. but I can't find any such object there.

1
  • will you please give detail error ? Commented Jul 4, 2014 at 3:43

3 Answers 3

1

If I understand your program correctly, you are trying to create a JSON object. As iCodez said in his answer, Python's format function treats the entire string as the format string (or template string, if you like). To override that, you can escape the format strings like this

"{{name:country{0},provinces:[{{$ref : Province,$id : province{1}}}]}}\n".format(c_n, p_n)

You will get something like the following if c_n and p_n are "Welcome" and "123"

{name:countryWelcome,provinces:[{$ref : Province,$id :   province123}]}
Sign up to request clarification or add additional context in comments.

Comments

1

You are starting your string with {name: so format need name as a key.

Please escape { before name.

https://docs.python.org/2/library/string.html#format-examples

Comments

1

str.format is treating the entire string as a format field because it begins with {name: and ends with }. Below is a demonstration with a simpler string:

>>> '{a:{0}}'.format(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'a'
>>>

To fix the problem, you can use the old % formatting:

text += "{name:country%i,provinces:[{$ref : Province,$id :   province%i}]}\n" % (c_n, p_n)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.