Appending a dictionary to a list in a a loop Python

后端 未结 5 1029
梦毁少年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)
    
    0 讨论(0)
  • 2020-11-30 00:28

    Just put dict = {} inside the loop.

    >>> dict = {}
    >>> list = []
    >>> for x in range(0, 100):
           dict[1] = x
           list.append(dict)
           dict = {}
    
    >>> print list
    
    0 讨论(0)
  • 2020-11-30 00:32

    You need to append a copy, otherwise you are just adding references to the same dictionary over and over again:

    yourlist.append(yourdict.copy())
    

    I used yourdict and yourlist instead of dict and list; you don't want to mask the built-in types.

    0 讨论(0)
  • 2020-11-30 00:37

    Let's say d is your dictionary. Here, if you do d.copy(). It returns shallow copy that doesn't work when you have nested dictionary into d dictionary. To overcome from this issue, we have to use deepcopy.

    from copy import deepcopy
    list.append(deepcopy(d))
    

    It works perfectly !!!

    0 讨论(0)
  • 2020-11-30 00:39

    You can also use zip and list comprehension to do what you need.

    If you want the dict values to start at one use range(1,100)

    l = [dict(zip([1],[x])) for x in range(1,100)]
    
    0 讨论(0)
提交回复
热议问题