0
# -*- coding: utf-8 -*-

import random, pprint
user = {}
USERINFO_STRUCT = {
    'id': '',
}

def client_new(id):
    global user

    newuser = USERINFO_STRUCT
    newuser['id'] = id
    user[id] = newuser

    pprint.pprint(user)
    print ""

client_new(1)
client_new(2)
client_new(3)

I want results:

{1: {'id': 1}}

{1: {'id': 1}, 2: {'id': 2}}

{1: {'id': 1}, 2: {'id': 2}, 3: {'id': 3}}

The results of that code execution is:

{1: {'id': 1}}

{1: {'id': 2}, 2: {'id': 2}}

{1: {'id': 3}, 2: {'id': 3}, 3: {'id': 3}}

How are you doing this?

My machine is Debian Linux 8.6 (Python 2.7.9).

help-info.de
  • 6,695
  • 16
  • 39
  • 41
meke meke
  • 3
  • 1
  • For a related question about lists, please see http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list – PM 2Ring Nov 12 '16 at 08:39

1 Answers1

4

In python, dictionaries and lists are copied by reference:

>>> a = [0]
>>> b = a
>>> b
[0]
>>> a
[0]
>>> b[0] = 2
>>> a
[2]
>>> b
[2]

So, b and a refer to the same list in the python memory and modifying one modifies the other.

So, what you can do is when you want to create another copy of a list or dictionary, make a copy. For a list:

>>> b = a[:]  # for a list

For a dictionary:

>>> b = a.copy()  # for a dictionary

So, in your code, what you need is to copy the USERINFO_STRUCT into the newuser using newuser = USERINFO_STRUCT.copy()

AbdealiLoKo
  • 3,261
  • 2
  • 20
  • 36
  • @mekemeke> it's not like this question has been posted a hundred times on this very website, with the exact same answer… Still, remember to accept it if it helped (click the tickmark on the left of the answer). – spectras Nov 12 '16 at 07:34