Combine dictionaries with lists, such as
I=20s=[]# define an empty list b={'d': i}# define a dictionary while i>0: i=i-1 b['d']=i# Update the value of a dictionary s.append (b)print(s)
Result is
[{'D': 0}, {'D': 0}, {'D': 0}, {'D': 0}, {'D': 0}, {'D': 0}, {'D': 0}, {'D': 0}, {'D': 0}, {'D': 0}, {'D': 0}, {'D': 0}, {'D': 0}, {'D': 0}, {'D': 0}, {'D': 0}, {'D': 0}, {'D': 0}, {'D': 0}, {'D': 0}]>>> s[0]['D']=90>>>s[{'D': 90}, {'D': 90}, {'D': 90}, {'D': 90}, {'D': 90}, {'D': 90}, {'D': 90}, {'D': 90}, {'D': 90}, {'D': 90}, {'D': 90}, {'D': 90}, {'D': 90}, {'D': 90}, {'D': 90}, {'D': 90}, {'D': 90}, {'D': 90}, {'D': 90}, {'D': 90}]
Just change the first element, too,
Each element of S is the same dictionary instance, changing the value of the dictionary in any one of the elements of the list.
If you change to:
I=20S=[] while i>0: i=i-1 b={'d ': i} to redefine B every time and assign value s.append (b)print(s)
Result is
[{'D': 19}, {'D': 18}, {'D': 17}, {'D': 16}, {'D': 15}, {'D': 14}, {'D': 13}, {'D': 12}, {'D': 11}, {'D': 10}, {'D': 9}, {'D': 8}, {'D': 7}, {'D': 6}, {'D': 5}, {'D': 4}, {'D': 3}, {'D': 2}, {'D': 1}, {'D': 0}]
It's the result we want.
The first case is that each list element is actually an instance, in fact the loop is just updating the value of the dictionary
Second case: Redefining the Dictionary every time
The pitfalls of dictionaries in Python