Python: how to change a list in a new dictionary without changing the original

I have a dictionary of lists:

dic = {"foo" : [1,3,5,6] , "bar" : [5, 3, 8, 4]}

      

I am trying to create a new dictionary of the reverse sequence of these lists without distorting the original

I've even tried things like

list1 =  dic["foo"]
list2 = list1.reverse()
newDic = {}
newDic["foo"] = list2

      

But it seems that dic["A"]

, list1

and list2

all point to the same memory location. In other words, it is dic["foo"]

also reversed in the process, which I don't want! is there an easy way to get around this?

+3


source to share


5 answers


If you want to make an entire dictionary try this one liner:

newDic = {key:value[::-1] for key,value in dic.iteritems()}

If you just want to make one list try this:



list1 =  dic["foo"]
newDic = {}
newDic["foo"] = list1[::-1]

      

list.reverse()

will change the list itself. Try list[::-1]

it and it will return a new copy of the inverted list

+2


source


list1.reverse()

is a turn in place. Instead, use a function reversed(list1)

that does not change the list it is called on.

In particular:



dic = {"foo" : [1,3,5,6] , "bar" : [5, 3, 8, 4]}
list1 = dic["foo"]
list2 = list(reversed(list1))
newDic = {}
newDic["foo"] = list2

      

Note that generatorreversed(list1)

returns and you want the complete list, so get called on it .list

+1


source


A task list2 = list1.reverse()

list.reverse () method will change the same list.

like

>>> a = [66.25, 333, 333, 1, 1234.5]
>>> a.reverse()
>>> a
[1234.5, 1, 333, 333, 66.25]

      

Return type reverse

-None

>>> a = [66.25, 333, 333, 1, 1234.5]
>>> b = a.reverse()
>>> b
>>> print b
None

      

So in your case list2 = None

.

Another problem is

you have access to , and the key f00

foo

+1


source


Another way:

list2 = []
for e in reversed(list1):
   list2.append(e)

      

list1.reverse () reverses the original list. rather, you can do it in a for loop.

+1


source


Your real problem is making a copy of the list, so you can do

list2 = list(list1)
list2.reverse()

      

or

list2 = list1[:]
list2.reverse()

      

0


source







All Articles