rhya
rhya

Reputation: 11

Write in output file in python

I have a list like as follows

list1 = [['abc',{2:1,3:4,5:6}],['xyz',{4:0,9:5,7:8}],.......]]

I want write the list in a o/p file in the following format:

'abc' 2:1 3:4 5:6
'xyz' 4:0 9:5 7:8

I tried different ways, but not able to get it in the above format.Let me also mention that len(list1) = 30000.Please suggest me an optimized way

Upvotes: 1

Views: 51

Answers (1)

xiº
xiº

Reputation: 4687

list1 = [['abc', {2: 1, 3: 4, 5: 6}], ['xyz', {4: 0, 9: 5, 7: 8}]]

with open('some.txt', 'w') as output_file:
    for k, v in list1:
        output_file.write('\'{}\' {}\n'.format(
            k, ' '.join('{}:{}'.format(key, val) for key, val in v.items())))

For Python 3 just use v.items().

Upvotes: 2

Related Questions