How to turn dictionary values into lists?

Question:

I keep searching for the answer to this but I can’t find it. Forewarning I’m new to Python so apologies in advance for noobiness :D.

Here’s the dictionary I have:

dict = {'test_key': 'test_value', 'test_key2': 'test_value2'}

And here’s the output I’m trying to achieve:

dict = {'test_key': ['test_value'], 'test_key2': ['test_value2']}

Thanks in advance for your help!

Asked By: livisaur

||

Answers:

You can loop through the items of the dictionary and assign them lists.

for key, value in dict.items():
    dict[ key ] = [ value ]
Answered By: Khalil

You can use dictionary comprehension:

dict = {key: [values] for key, values in dict.items()}

new dict will be:

{‘test_key’: [‘test_value’], ‘test_key2’: [‘test_value2’]}

Answered By: ShivaGaire
if __name__ == '__main__':
    dict = {'test_key': 'test_value', 'test_key2': 'test_value2'}
    for key, value in dict.items():
        dict[key] = [value]

Few ways you can go about this in the order of fastest to slowest implementation:

Dict comprehension:

{
    k: [v] for k, v in dict.items()
}

Simple for:

for k, v in dict.items():
    dict[k] = [v]

Python map():

dict(map(
    lambda x: (x[0], [x[1]]), dict.items()
))

result:

{‘test_key’: [‘test_value’], ‘test_key2’: [‘test_value2’]}

Answered By: anupamkrishna
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.