Zhicong Pan Zhicong Pan - 3 months ago 5
Python Question

Write a dictionary containing lists in values into text file with keys repeated for each element in the list

I am new to python and I am working on a project that needs to write a dictionary into a text file. The format is like:

{'17': [('25', 5), ('23', 3)], '12': [('28', 3), ('22', 3)], '13': [('28', 3), ('23', 3)], '16': [('22', 3), ('21', 3)], '11': [('28', 3), ('29', 1)], '14': [('22', 3), ('23', 3)], '15': [('26', 2), ('24', 2)]}.


as you can see, the values in the dictionary are always lists. I would like to write the below into the text file:
17, 25, 5 \n
17, 23, 3 \n
12, 28, 3 \n
12, 22, 3 \n
13, 28, 3 \n
13, 23, 3 \n
...
\n stands for a new line

Which means, the keys to be repeated for each value inside the list that 'belongs' to those keys. The reason is because I need to read the text file again into database to do further analysis.
Have try searching for an answer for the past few days and tried many ways, just cannot make it into this format. Appreciate if any of you have a solution for this.
Thanks a lot!

Answer
>>> for k, v in data.items():
...     for t in v:
...        print "%s, %s, %s" % ((k,) +t)
... 
11, 28, 3
11, 29, 1
13, 28, 3
13, 23, 3
12, 28, 3
12, 22, 3
15, 26, 2
15, 24, 2
14, 22, 3
14, 23, 3
17, 25, 5
17, 23, 3
16, 22, 3
16, 21, 3
>>> 

First get each key and value (which are tuples). Then loop through the tuples and print each tuple value with the key. Note that dictionaries are not ordered, so the results will not likely be in the order of your dictionary

Comments