2

I am trying to set a dictionary for the staff's salary in Python. I want to create two functions, getname() and getsalary() so I tried:

empDic={}

def setname(n):

empDic={'n':''}

And then in python interactive 2.7 I typed:

>>>setname('marson')

>>>print empDic

{}

The result is still an empty dictionary, How can I deal with that?

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Zhou Jie
  • 31
  • 1
  • 1
  • 2
  • 3
    Your indentation is wrong. In any case, the empDic inside the function will create a local variable. To use/update the global one, you need to use the `global` keyword. Also, dictionaries with only keys are usually a sign that you need `set`s instead. – Noufal Ibrahim May 15 '15 at 14:24
  • Not sure the dupe is a great fit for this, using global is not going to work and there are more things wrong in the OP's code than scope issues – Padraic Cunningham May 15 '15 at 14:36

1 Answers1

2

You would need to modify the original dict:

empDic={}

def setname(d, n):
   d[n] = ""

setname(empDic,"marson")

print(empDic)
{'marson': ''}

You are creating a new local variable empDic in your function, you are also using a string "n" not the name n passed in to the function.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321