如何使用for循环从第一个Python字典构建第二个Python字典?

问题描述 投票:0回答:1

由于您无法使用for循环从字典中删除项目,而没有'字典更改大小'警告,因此我需要将除一个元素之外的所有元素复制到另一个元素。这主要是因为mongoDB不接受以$开头的键,而我需要将其写入数据库。没关系,不需要键。

我不能使用'del'或'pop',所以我只需要根据键是什么就从字典中删除项目。

我无法解决如何正确执行此操作,但这是我所拥有的:

# Let's test the endpoint quickly
    if test_endpoint() == 200:

        # Endpoint is alive, so lets consume it
        raw_response = requests.get('https://api.tfl.gov.uk/StopPoint/490009333W/arrivals')
        json_response = raw_response.json()
        cleaned_response = { key:value for (key,value) in json_response[0].items() }

        fresh_response = {}
        # Apparently we need to strip $ symbols from the start of keys because mongo complains
        for key in cleaned_response.items():
            print(key)
        #   if not key.startswith('$'):
        #       fresh_response = key

        # print(fresh_response)


        # mongo.db.arrivalPredictions.insert(cleaned_response)

        return render_template('index.html', response=fresh_response)
python dictionary flask
1个回答
1
投票

这将“克隆”字典。如果您还有其他问题,请告诉我:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

new_dictonary = {}

print("new_dictonary before:", new_dictonary)

for i in thisdict:
    new_dictonary[i] = thisdict[i]

print("new_dictonary after:", new_dictonary)
© www.soinside.com 2019 - 2024. All rights reserved.