0

I have a list of dictionaries:

list = [{"id":2, "date": "2018-07-12"}]

Now I want to generate some nice output and have a function for it:

def generateOutput(myList):  
   outputList = []        
   for l in myList:            
      l['date_short'] = "Jul-12"
   outputList.append(l)

   return outputList

And here's where the desaster starts:

output = generateOutput(list)

output is fine but list that I need for further calculation and shouldn't have the date_short at all got a new key and is:

list = [ {"id":2, "date": "2018-07-12", "date_short": "Jul-12" }]

How to overcome this?

VengaVenga
  • 680
  • 1
  • 10
  • 13
  • 1
    Make a copy of the list? – khelwood Oct 18 '18 at 22:44
  • I don't understand. If the output is fine, what's the problem? If you don't want the output to have a date_short key, why are you doing `l['date_short'] = "Jul-12"`? Can you provide an example of how your desired output differs from your actual output? – Kevin Oct 18 '18 at 22:48
  • You can pass a copy of the list instead: output = generateOutput(list[:]) – acw1668 Oct 18 '18 at 23:11
  • > What's the problem? This is only for demonstration. I need a list with the original data that stays in the core module and one I send to the output app. – VengaVenga Oct 19 '18 at 07:00
  • > you can pass a copy of the list instead: output = generateOutput(list[:]) Nope. Careful, does not working. Slicing seems not work in that context (list of dictionary). [link](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – VengaVenga Oct 19 '18 at 07:05

2 Answers2

4

You are modifying the dictionaries in myList in-place. Instead, you probably want to copy them individually before adding new values to them. Try this:

def generateOutput(myList):
    outputList = []
    for l in myList:
        output = l.copy()
        output['date_short'] = "Jul-12"
        outputList.append(output)
    return outputList

Also, you should avoid naming a variable list since list is the name of a predefined type in Python.

vthorsteinsson
  • 352
  • 2
  • 5
0

Pass a copy of the variable to the function by using the copy module.

import copy

list = [{"id":2, "date": "2018-07-12"}] 

def generateOutput(myList):  
   outputList = []        
   for l in myList:            
      l['date_short'] = "Jul-12"
   outputList.append(l)

   return outputList

generateOutput(copy.copy(list))
Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42