0

Newbie python programmer here, so i apologise if this question has been asked but i could not find an answer that i understood and could apply to my code.

basically i have a dictionary my_dict which is of len(x), where 4 < x < 100.

the dictionary is in the form:

{ 0: (bg_colour, text_colour), ..., x: (bg_colour, text_colour)) }

where the values of bg_colour and text_colour will be updated as the program runs.

Later in my code i want to call a function to draw rectangles on a canvas based on this dictionary, and I am meant to use the **kwargs as an argument to make this happen. I have tried using: func(**mydict), but get error: keywords must be strings.

So my question is how can I transform my_dict into a form where it is recognisable by **kwargs? From what I have read i have to get it into a string form such as: my_dict = '0=(bg_colour, text_colour), ..., x=(bg_colour, text_colour)' and i'm thinking perhaps because the values of my_dict is tuples in this case, that may be the problem? perhaps to work around this i should make two dicts; one for bg and one for text. but this would mean entering twice as many **kwargs into my function, and i would prefer not to do that.

Thanks in advance for any answers.

Abhishek-Saini
  • 733
  • 7
  • 11
  • 2
    It's because 0 is one of your keys, keys must be strings in order to map to a parameter in a function. https://stackoverflow.com/a/47568402/929999 – Torxed May 28 '20 at 06:18
  • https://stackoverflow.com/questions/5710391/converting-python-dict-to-kwargs – NewPythonUser May 28 '20 at 06:19

1 Answers1

0

You could build a new dictionary where you've converted the keys to strings

>>> def func(**mydict):
...     print(mydict)
... 
>>> my_dict = {0:(30,12),1:(99,99), 2:(16,255)}
>>> func(**{str(key):val for key,val in my_dict.items()})
{'0': (30, 12), '1': (99, 99), '2': (16, 255)}
>>> 

But why not just define func to take a dict? If this function is taking keyword arguments, its a pretty good bet its not expecting integers as parameters, and if this kw dict isn't holding parameters, it shouldn't be a kw dict in the first place, I would think.

tdelaney
  • 73,364
  • 6
  • 83
  • 116