0

Can someone tell me in the code below, how to prevent "Cvalue" being appended to "fred" when I only want it to be appended to result[key]?
I'm using python 2.7, but python 3 behaves the same.


#!/usr/bin/env python

hdict = {52951331: [5], 23396132: [4], 82982473: [19, 37], 126988879: [20] }
Cdict = {23396132: [19, 37], 82982473: [4], 126988879: [5], 52951331: [20]}

result = {}
for key, value in hdict.iteritems():
    if key in Cdict:
        result[key] = value
        for Cvalue in Cdict[key]:
            fred = value
            print 'fred1: ', fred
            result[key].append(Cvalue)
            print 'fred2: ', fred
  • `fred = value` doesn't make a copy of `value`. Same with `result[key] = value`. See ["Facts and myths about Python names and values"](http://nedbatchelder.com/text/names.html). – user2357112 Jun 30 '16 at 04:35
  • This is not even about dicts, but about lists. The dict just obfuscates things: replace it by e.g. `some_value` and you'll have the same problem. –  Jun 30 '16 at 04:57

1 Answers1

0

why dont you try to use copy.

#!/usr/bin/env python

import copy

hdict = {52951331: [5], 23396132: [4], 82982473: [19, 37], 126988879: [20]}

Cdict = {23396132: [19, 37], 82982473: [4], 126988879: [5], 52951331: [20]}
result = {}

for key, value in hdict.iteritems():

if key in Cdict:

    result[key] = value
    for Cvalue in Cdict[key]:
        fred = copy.copy(value)
        print 'fred1: ', fred
        value.append(Cvalue)
        print 'fred2: %s, value: %s' % (fred, value)
Angelo
  • 61
  • 1
  • 8
  • Since `value` is a `list`, `fred = value[:]` is probably simple enough. –  Jun 30 '16 at 04:58