Advertisement
Programmin-in-Python

Formatting Dictionary items and writing them to a file

Jan 4th, 2021
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.56 KB | None | 0 0
  1. def dict2file(d, filename):
  2.     D1, D2 = dict(), dict()
  3.  
  4.     for i in d:
  5.         if isinstance(i, int):
  6.             D1[i] = d[i]
  7.         else:
  8.             D2[i] = d[i]
  9.  
  10.     with open(f"{filename}.txt", "w") as file:
  11.         L1, L2 = sorted(D1.items()), sorted(D2.items())
  12.  
  13.         if any(L1):
  14.             for i in L1:
  15.                 file.write(f"{i[0]} -> {i[1]}\n")
  16.  
  17.         elif any(L2):
  18.             for i in L2:
  19.                 file.write(f"{i[0]} -> {i[1]}\n")
  20.  
  21.     print("File Written Successfully")
  22.  
  23. d = {"12": 2,"11": 1,"A":31,'a': 30,'c': 1,'b': 17,'e': 9,'d': 52,'f': 11,
  24.     'g': 1,'h': 23,'13': 16,'k': 2,'l': 8}
  25. dict2file(d, "filename")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement