-2

I would like to store the multiple dict inside the list. dict has the same key.

>>> m = {}

>>> l = [] 

>>> for i in range(4):                                                                                                                                                  
...     m["i"] = i+2                                                                                                                                                    
...     m["j"] = i+5                                                                                                                                                    
...     l.append(m)                                                                                                                                                     
...                                                                                                                                                                     
>>> print(l)                                                                                                                                                            
[{'i': 5, 'j': 8}, {'i': 5, 'j': 8}, {'i': 5, 'j': 8}, {'i': 5, 'j': 8}] 

But, I want to know store as below 

[{'i': 2, 'j': 5}, {'i': 3, 'j': 6}, {'i': 4, 'j': 7}, {'i': 5, 'j': 8}]
Rakesh
  • 81,458
  • 17
  • 76
  • 113
GOVINDREDDY
  • 23
  • 1
  • 7
  • This is absolutely possible in python. Please provide a [mcve] for your issue, with a _specific_ description of the problem, and the _code_ for what you've tried so far – G. Anderson Nov 21 '19 at 19:12
  • Move `m = {}` to the first line after you enter the for loop. – Tony Tuttle Nov 21 '19 at 19:13
  • 1
    The marked duplicate deals with lists; you have the same trouble with dictionaries, also mutable. You appended four copies of the same object to your list. – Prune Nov 21 '19 at 19:18

2 Answers2

1
l = []

for i in range(4):
    l.append({'i': i+2, 'j': i+5})

print(l)

outputs:

[{'i': 2, 'j': 5}, {'i': 3, 'j': 6}, {'i': 4, 'j': 7}, {'i': 5, 'j': 8}]

The problem in your code is that m["i"] and m["j"] points to the same memory address on each iteration, and thats why you get all the elements to have the same value in l

nonamer92
  • 1,887
  • 1
  • 13
  • 24
0

You should create a new empty dictionary in each iteration of the loop. In your current version, m points to the same object throughout the entire execution, so the list simply contains 4 references to that object.

Dave Costa
  • 47,262
  • 8
  • 56
  • 72