'python automatically change a variable from list to string inside a for loop

Python automatically changes a variable from list to str inside a for loop so I got an error when I append to the list. Why does this happen?

error screen



Solution 1:[1]

By looking at your provided question and the output, I think that you are basically trying to swap the dictionary values of the given one.

So, the code for that is :

def func(dct):
  new_dct = {}
  for key, values in dct.items():
    for value in values:
      if value in new_dct:
        new_dct[value].append(key)
      else:
        new_dct[value]=[key]

  return (new_dct)  

dct = {'local': ['admin', 'userA'],
      'public': ['admin', 'userB'],
      'administrator': ['admin']}

print(func(dct))

I guess this should work for you! Considering Upvoting if found helpful!

Solution 2:[2]

Just change line 14 to ug = [groups,].

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Samir Tak
Solution 2 Sourin Karmakar