-1
data = []
dic = dict.fromkeys(['a', 'b', 'c'], 0)

value = 1
for i in range(3):
    key = list(dic.keys())
    for j in range(len(dic)):
        dic[key[j]] = value
        value += 1
    data.append(dic)
    
for i in data:
    print(i)

In this code, I expexted like this.

{1, 2, 3}
{4, 5, 6}
{7, 8, 9}

but the result is

{7, 8, 9}
{7, 8, 9}
{7, 8, 9}

How can i fix this code to get result that i expected?

  • 4
    What you expect is not a dictionary. A dictionary has a key value pair. Please specify more clearly what you want to achieve. – binaryescape Jul 31 '23 at 15:05
  • Does this answer your question? [How to copy a dictionary and only edit the copy](https://stackoverflow.com/questions/2465921/how-to-copy-a-dictionary-and-only-edit-the-copy) – slothrop Jul 31 '23 at 15:08
  • there is only one dictionary in your list, which you add 3 times. You need to add a distinct dictionary each time – juanpa.arrivillaga Jul 31 '23 at 15:08

2 Answers2

1

You only have one dictionary, dic. You have created a list with three references to it. To get the results you want, change your code to create a new dictionary for each iteration of the main loop

alexis
  • 48,685
  • 16
  • 101
  • 161
0

Instead of :

    data.append(dic)

Use:

    data.append(dic.copy())

This will create a new object, instead of adding a reference to dic to your list.