简体   繁体   中英

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 ao/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

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM