Convert Python dictionary which has list as values into simple dictionnary

Viewed 39

I have a dictionary which has a list as value like following:

dict = {"a":["b","c","d"]}

And I want to have this form :

dict = {"a":"b","a":"c","a":"d"}
2 Answers

From your comments, you want to write the dict content to a csv file. There is no need for flattening anything:

d = {"a":["b","c","d"]}    # never use dict or list as a variable name to not hide builtins
with open("file.csv", "w", newline="") as fd:
    wr = csv.writer(fd)
    for k,v in d.items():
        for x in v:
            wr.writerow((k,x))

Since dictionaries have unique keys you can't create directories. I think the list of tuples would be a better idea. Here's a sample on how it can be achieved.

dict = {"a":["b","c","d"]}

newList = list()

for key, value in dict.items():
    for i in value:
        newList.append((key, i))

print(newList)

Output for this as follows.

[('a', 'b'), ('a', 'c'), ('a', 'd')]

Hope this helps.

Related