Emilia Clarke
Emilia Clarke

Reputation: 85

How to change values in a dictionary to lists instead of strings

I have:

dict1 = {'usa' : '10', 'japan' : '20', 'canada' :'30'} 

And I'm trying to change the values to show as lists, like:

dict1 = {'usa' : [10], 'japan' : [20], 'canada' : [30]} 

I've tried iterating over the values in the dictionary but the output hasn't changed...

for v in dict1.values():
    v = list(v) 

Upvotes: 1

Views: 28

Answers (2)

Salvador Dali
Salvador Dali

Reputation: 222481

Just simply iterating through the dictionary:

for i in dict1:
    dict1[i] = [int(dict1[i])]

print dict1

which will give you:

{'canada': [30], 'japan': [20], 'usa': [10]}

Also you can use dictionary comprehensions, (as suggested by iCodez), but for a person new to python this might be harder to grasp, also shorter.

Upvotes: 0

user2555451
user2555451

Reputation:

Your current code is not working because your loop is just repeatedly reassigning the name v to list(v). It is not actually changing the values inside dict1.

The easiest way to do what you want is to use a dict comprehension:

>>> dict1 = {'usa' : '10', 'japan' : '20', 'canada' :'30'}
>>> {k:[int(v)] for k, v in dict1.items()}
{'japan': [20], 'canada': [30], 'usa': [10]}
>>>

Note that in Python 2.x, you should do dict1.iteritems() to avoid creating an unnecessary list.

Upvotes: 1

Related Questions