Python dictionary update: content overwritten

I have written following code:

collect2={}
dict1={}
dict2={}
dict1["id"]=1
dict1["title"]="Task 1"
dict1["is_completed"]="true"
dict2["id"]=2
dict2["title"]="Task 2"
dict2["is_completed"]="false"
collect2.update(dict1)
collect2.update(dict2)
print(collect2)

The output is

{'id': 2, 'title': 'Task 2', 'is_completed': 'false'}     

However, I would expect the content of dict1 and dict2 to be in collect2.

Can you help me what I need to change so that this happens?

Thank you for your help!

Upvotes: 1

Views: 36

Answers (2)

Ratnesh
Ratnesh

Reputation: 1700

@ba5h has suggested corrected approach, but again if you want to restrict to one dictionary, you can use the below code

dict1={}
dict1["id"]=[1]
dict1["title"]=["Task 1"]
dict1["is_completed"]=["true"]

if "id" in dict1:
    dict1["id"].append(2)
if "title" in dict1:
    dict1["title"].append("Task 2")
if "is_completed" in dict1:
    dict1["is_completed"].append("false")

Upvotes: 0

ba5h
ba5h

Reputation: 97

A dictionary is a pairing of a key with a value. The issue you have is that dict1 & dict2 have the same keys, and you can't have the same key pointing to two different things - what would you expected to get when you do collect2[id]?

Possibly you're looking to put two dictionaries in a list? So you could do collection = [dict1, dict2] and then do collection[0]['id'] to return 1?

Upvotes: 3

Related Questions