Home > Software design >  python: Turn dictionary int values into list [closed]
python: Turn dictionary int values into list [closed]

Time:09-17

I have a dictionary like

num ={'a':45,
      'b':5,
      'c':6
       } 

and I want to turn it into:

num ={'a':[45],
      'b':[5],
      'c':[6]
     }

How can I do that? Thank you!

I have tried this way:

for letter in num:
    num[letter] = list(map(int, str(num[letter])))

but get:

{'a': [4, 5], 'b': [5], 'c': [6]}

CodePudding user response:

In the future, please include some code you've tried to solve this with.

As for the answer, you could use dictionary comprehensions:

>>> {k: [v] for k, v in {'a': 45, 'b': 5, 'c': 6}.items()}
{'a': [45], 'b': [5], 'c': [6]}
  • Related