Appending a dictionary to a list in a a loop Python

后端 未结 5 1057
梦毁少年i
梦毁少年i 2020-11-29 23:42

I am a basic python programmer so hopefully the answer to my question will be easy. I am trying to take a dictionary and append it to a list. The dictionary then changes val

5条回答
  •  忘掉有多难
    2020-11-30 00:18

    When you create the adict dictionary outside of the loop, you are appending the same dict to your alist list. It means that all the copies point to the same dictionary and you are getting the last value {1:99} every time. Just create every dictionary inside the loop and now you have your 100 different dictionaries.

    alist = []
    for x in range(100):
        adict = {1:x}
        alist.append(adict)
    print(alist)
    

提交回复
热议问题