Home > Net >  Update Dictionary with python for loop
Update Dictionary with python for loop

Time:08-15

I try to update a dictionary through for loop, but only the first item is added to the dictionary rest are lost, I am pretty new, please advise what i am doing wrong.

#Data
{'_id': ObjectId('62f7e5a34d39c21994d31a26'), 'company': 'xyz', 'product': 'Testing', 'offered': 'tests'}
{'_id': ObjectId('62f7e8cbeb39e8c9402c2db8'), 'company': 'xyz', 'product': 'Testing', 'offered': 'tests1'}
{'_id': ObjectId('62f7ea2c4d39c21994d31a27'), 'company': 'xyz', 'product': 'Testing', 'offered': 'tests'}
{'_id': '1', 'company': 'xyz', 'product': 'Testing', 'offered': 'tests'}
{'_id': '2', 'company': 'xcyz', 'product': 'Testing', 'offered': 'tests'}
{'_id': '3', 'company': 'xcyz', 'product': 'Testing', 'offered': 'tests'}
{'_id': '5', 'company': 'xcyz', 'product': 'Testing', 'offered': 'tests'}


upd=collection.find() # data fetched from mongo DB

new_dict = {} # creating a new dictionary to store the filtered data from MongoDB
for i in  upd:
    test_dict.update(i)
    if i['_id'] not in ['1','2','3','5']:
        new_dict.update(i)  #update the dictionary after filtering through iteration.

print(test_dict)


Output: {'_id': ObjectId('62f7ea2c4d39c21994d31a27'), 'company': 'xyz', 'product': 'Testing', 'offered': 'tests'}

expected Output: 
{'_id': ObjectId('62f7e5a34d39c21994d31a26'), 'company': 'xyz', 'product': 'Testing', 'offered': 'tests'}
{'_id': ObjectId('62f7e8cbeb39e8c9402c2db8'), 'company': 'xyz', 'product': 'Testing', 'offered': 'tests1'}
{'_id': ObjectId('62f7ea2c4d39c21994d31a27'), 'company': 'xyz', 'product': 'Testing', 'offered': 'tests'}

CodePudding user response:

You'd want a list of dictionaries:

new_list = [] # creating a new list to store the filtered data from MongoDB
for i in  upd:
    if i['_id'] not in ['1','2','3','5']:
        new_list.append(i)  # append to new_list
print(new_list)
  • Related