BitFreak
BitFreak

Reputation: 416

Append to dictionary in Python

I have the below code and would expect my dictionary tag to have as many entries as I get .s printed to the screen. I, however, end up with a single entry only, as shown by the bottom print. Each id is unique, i.e. I expect a separate entry per id. How do I correctly do I do this correctly?

tag={}
for id in tags:

    ipm = {"test":[{ "name": "TestOne", "risk": 3},{ "name": "TestTwo", "risk": 2},{ "name": "TestThree", "risk": 1}]}
    post={"post_1":ipm}

    tag={id:post}
    x={}
    tag.update(tag)
    print(".")

print(json.dumps(tag))

Upvotes: 0

Views: 40

Answers (1)

Thomas
Thomas

Reputation: 5138

The reason your dictionary only contains one entry is because you reassign it

tag={id:post}

before you update. Just update it with the new value.

tag.update({id:post})

Upvotes: 1

Related Questions