0

I am new to python. When I was playing around with the code, I found this.

Source Code:

dic = {}
mem_dic = {}

def set_op(ind, data):
    global dic, mem_dic
    key, value = data.split()
    dic[key] = int(value)
    mem_dic[ind] = dic
    print(ind, "====", mem_dic)

set_op(0, 'aaa 1')
set_op(1, 'bbb 2')

Expected Output:

0===={0:{'aaa':1}}
1===={0:{'aaa':1},1:{'aaa':1,'bbb':1}}

Actual Output:

0===={0:{'aaa':1,'bbb':1}}
1===={0:{'aaa':1,'bbb':1}}

Could anyone please explain the reason for this behavior. And what changes should I incorporate to get the expected output.

keerthana
  • 85
  • 1
  • 2
  • 13
  • Can you explain what you are trying to do here? –  Jan 24 '18 at 08:49
  • @LutzHorn here I am trying to keep a track of the changes in the dictionary during an iteration – keerthana Jan 24 '18 at 09:06
  • Note that your stated actual output doesn't match the actual output I get when I run it on python2.7; not sure if that's an artifact of changing stuff after the edit or not, but that's not helping your question. – Foon Jan 24 '18 at 13:17

2 Answers2

1

You're not gaining anything by having a global for dic. You have one dic in your code and you add it to mem_dic twice. If you want two dicts inside mem_dic, don't add the same dict twice.

mem_dic = {}

def set_op(ind, data):
    global mem_dic
    key, value = data.split()
    dic = { key: int(value) } # a new dictionary
    mem_dic[ind] = dic
    print(ind, "====", mem_dic)
>>> set_op(0, 'aaa 1')
0 ==== {0: {'aaa': 1}}
>>> set_op(1, 'bbb 2')
1 ==== {0: {'aaa': 1}, 1: {'bbb': 2}}
khelwood
  • 55,782
  • 14
  • 81
  • 108
1

Create new instance of dictionary by changing this line mem_dic[ind] = dict(dic)

dic = {}
mem_dic = {}

def set_op(ind, data):
    global dic, mem_dic
    key, value = data.split()
    dic[key] = int(value)
    mem_dic[ind] = dict(dic)
    print(ind, "====", mem_dic)

set_op(0, 'aaa 1')
set_op(1, 'bbb 2')

Output

(1, '====', {0: {'aaa': 1}, 1: {'aaa': 1, 'bbb': 2}})

Artier
  • 1,648
  • 2
  • 8
  • 22