pythonarrayslistdictionarymultivalue

Converting dictionary with multiple strings into 2D Array/List


Similar questions:

How to convert a dict of lists to a list of tuples of key and value in python?

Python convert dictionary where keys have multiple values into list of tuples

My question is very similar to the above links, however the answers there do not work for me because instead of 1 letter values, I have worded strings - e.g.

{"My": "[dog, cat, bird]", "is":"[cute]", "Hi":[], "Hello":"[World]"}

I want this to be like:

[('My'),('dog')],[('My), ('cat')], [('My'),('bird')], [('is'), ('cute')], [('Hello', ('World')]

The solutions to the above links does not work because it iterates through every letter in the value, whereas I want the entire word. I have tried using split() to split each value by a comma and then allocate it a value in a new array however I'm having complications with that as I am not familiar with dictionaries in python so unable to come up with a working solution.


Solution

  • I think nested loop inside list comprehension still works even with worded strings as python sees single letter value also as a string

    data = {"My": ["dog", "cat", "bird"], "is":["cute"], "Hi":[], "Hello":["World"]} 
    
    lst = [(k, v) for k in data for v in data[k]]
    

    Update: If the dictionary value is a string instead of a list, you can do some string manipulation to remove the brackets (data[k][1:-1]) and split the string by commas so that it can be iterated as a list (.split(", "))

    lst = [(k, v) for k in data if not isinstance(data[k], list) for v in data[k][1:-1].split(", ")]