Eilz Eilz -4 years ago 268
Python Question

Python, How to multi dict declaring variables function

I need to do like this.

def multiDecare(num = eval(input('Enter number of variables : '))):
I = 0
get_var = {}
while I < num:
e = 'var'+str(I)
get_var.update(dict.fromkey(e))
return get_var


result when print like :

{'var1':'','var2':'''var3':'''var4':'''var5':''}

Answer Source

You have an infinite loop because you're not incrementing I.

To avoid all that while stuff (everybody gets caught once in a while), you could use a forloop, but even better, you could create your dictionary in 1 line using a gen-comprehension inside from_keys

def multiDeclare(num):
  return dict.fromkeys(("var{}".format(i) for i in range(1,num+1)),"")

or with dict comprehension:

  return  {"var{}".format(i+1):"" for i in range(num)}

with num == 5, the function returns:

{'var5': '', 'var4': '', 'var2': '', 'var1': '', 'var3': ''}

Aside:

  • don't use eval(input("")), it's unsafe and in that case int(input("")) does the same thing
  • don't pass function calls as default parameters, only values (immutable is best).
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download