如何在python列表中保留查询参数

时间:2018-04-04 00:56:59

标签: python list

if __name__ == '__main__':
    testcases = {}
    params = {}
    tests = {}
    expectations ={}
    append_all_tests = []
    main_input = {}
    testcases["queries"] = ["obama", "london"]
    params["locale"] = "US"
    expectations["type"] = ["president", "city"]

    for i, q in enumerate(testcases['queries']):
        tests["parameters"] = params
        tests["expectations"] = expectations
        tests["query"] = q
        append_all_tests.insert(i, tests)
    main_input["tests"] = append_all_tests
    print main_input

我的出局是:{'tests': [{'query': 'london', 'expectations': {'type': ['president', 'city']}, 'parameters': {'locale': 'US'}}, {'query': 'london', 'expectations': {'type': ['president', 'city']}, 'parameters': {'locale': 'US'}}]}

我希望它是:

{'tests': [{'query': 'obama', 'expectations': {'type': ['president', 'city']}, 'parameters': {'locale': 'US'}}, {'query': 'london', 'expectations': {'type': ['president', 'city']}, 'parameters': {'locale': 'US'}}]}

如何循环列表中的查询数量?请帮忙。

1 个答案:

答案 0 :(得分:0)

正如@zwer所说,这种情况正在发生,因为您将同一个对象(tests)多次插入append_all_tests。您可以通过在每次迭代中创建一个新的dict对象来解决这个问题:

if __name__ == '__main__':
    testcases = {}
    params = {}
    expectations ={}

    append_all_tests = []
    main_input = {}

    testcases["queries"] = ["obama", "london"]
    params["locale"] = "US"
    expectations["type"] = ["president", "city"]

    for i, q in enumerate(testcases['queries']):
        tests = {}
        tests["parameters"] = params
        tests["expectations"] = expectations
        tests["query"] = q

        append_all_tests.insert(i, tests)

    main_input["tests"] = append_all_tests
    print main_input

示例输出:

{'tests': [{'query': 'obama', 'expectations': {'type': ['president', 'city']}, 'parameters': {'locale': 'US'}}, {'query': 'london', 'expectations': {'type': ['president', 'city']}, 'parameters': {'locale': 'US'}}]}