Warm tip: This article is reproduced from stackoverflow.com, please click
python-2.7

How to write a dictionary key values into text file using python

发布于 2020-04-07 23:15:09

Here in my code i want to write a dictionary values into text values,In my dictionary values are in list of tuples.for ex: 'e': [(1, 2), (2, 6), (2, 11)],i want to write a 'e' letter in 1st line 2nd position,second line 6th position and 2nd line 11th position in a text file using python.can any one please guide me how to do this.

Given below is my problem:

d={'a': [(2, 2)], ' ': [(1, 6), (2, 4)], 'c': [(2, 8)], 'e': [(1, 2), (2, 6), (2, 11)], 'd': [(1, 11)], 'i': [(2, 3)], 'h': [(1, 1), (2, 1)], 'm': [(2, 10)], 'l': [(1, 3), (1, 4), (1, 10), (2, 7)], 'o': [(1, 5), (1, 8), (2, 9)], 'r': [(1, 9)], 'w': [(1, 7), (2, 5)]}

with open("C:\Users\Desktop\hellotext.txt","w") as f:
    for k,v in d.items():
        for line_no,letter_pos in v:
            print k,line_no,"lllll",letter_pos
            f.write()  #how to write a file
Questioner
gowthami
Viewed
69
Fuji Komalan 2020-02-01 03:34
d={'a': [(2, 2)], 'b': [(1, 6), (2, 4)], 'c': [(2, 8)], 'e': [(1, 2), (2, 6), (2, 11)], 'd': [(1, 11)], 'i': [(2, 3)], 'h': [(1, 1), (2, 1)], 'm': [(2, 10)], 'l': [(1, 3), (1, 4), (1, 10), (2, 7)], 'o': [(1, 5), (1, 8), (2, 9)], 'r': [(1, 9)], 'w': [(1, 7), (2, 5)]}


max_raw = max( raw for nested_key in d.values() for raw,col in nested_key )
max_col = max( col for nested_key in d.values() for raw,col in nested_key )


# Creating array of raw=max_raw column=max_col

arr = [ ]

for raw in range(max_raw):

  arr.append( [''] * max_col )



print(arr)
"""
arr = [
['', '', '', '', '', '', '', '', '', '', ''], 
['', '', '', '', '', '', '', '', '', '', '']

]
"""

for char in d:

  positions = d[char]

  for x,y in positions:

    arr[x-1][y-1] = char

print(arr)

"""
[
  ['h', 'e', 'l', 'l', 'o', 'b ', 'w', 'o', 'r', 'l', 'd'], 
  ['h','a', 'i', 'b ', 'w', 'e', 'l', 'c', 'o', 'm', 'e']
]
"""


for raw in arr:

  line = ''.join(raw)
  print(line)

"""
hellobworld
haibwelcome
"""

fh = open('myfile.txt','w'):


for raw in arr:

  line = ''.join(raw)

  fh.write(line)
  fh.write('\n')

fh.close()