Home > Mobile >  How to turn dictionary values into lists?
How to turn dictionary values into lists?

Time:06-28

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!

CodePudding user response:

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

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

CodePudding user response:

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']}

CodePudding user response:

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

CodePudding user response:

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']}

  • Related