0

I'm looking to assign items to variables using a loop, where the names of the variables are already predetermined from a list. I've got a list set up, and I'm having issues within the loop. My code is similar to this:

dict_Name = { 'a', 'b', 'c', ... , 'k', 'l'}

for input_x in list_Name:

    dict_Name['self.var_'+input_x] = round(float(eval('self.ui.inp_'+input_x).text()), 2)

    print ('self.var'+input_x)

Where the dictionary goes from 'a' to 'l'. Here, the rounded floating number is coming from user input (GUI created with PyQt) where the input value name is "inp_a", for example. I'm looking to assign the "inp_a" value to "var_a", but I'm having trouble with this.

The current error is that the " 'set' object does not support item assignment". I'm assuming this means I can't use the dictionary tool to assign variables from the user input, but I'm not sure about that.

Any help is much appreciated.

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
C. Art
  • 5
  • 1
  • you are creating a `set` instead of a `dict` in your first line. That's why you get the `'set' object does not support item assignment'` error in line 3. – Felix Apr 03 '17 at 23:52
  • 2
    [Why you don't want to dynamically create variables](http://stupidpythonideas.blogspot.cl/2013/05/why-you-dont-want-to-dynamically-create.html) – Zero Piraeus Apr 03 '17 at 23:58
  • Okay, I understand that now. I was looking for a quick way to make all the variables, but I see now why dynamically creating them isn't the best idea. Between MS excel and MS word I was able to set it up to set the variables pretty quickly. Thank you. – C. Art Apr 04 '17 at 13:00

1 Answers1

0

In your first line you've created a set:

dict_Name = { 'a', 'b', 'c', ... , 'k', 'l'} # not a dict

dict is a mapping of items into other items, where do you see any mapping here? For example this is a dict:

real_dict = {'a' : 'val_a', 'b' : 'val_b'}

set on the other hand is a collection of unique objects, and that's what you've created on the first line.

mateuszlewko
  • 1,110
  • 8
  • 18