Python Forum

Full Version: Print data in rows and columns
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have make a script in python having below output.

Output:
Output:
('User ID' 'Hits', {'1982641': 10, '105350': 9, '1008313': 7, '2073270': 11, '2073279':10})
I want to sort by hits and display in row and columns, How could i do that:
Output:
Userid Hits 1008313 7 105350 9 1982641 10 2073279 10 2073270 11
try pprint
import pprint
pprint = prettyprinter.pprint
pprint(print what you want)
https://docs.python.org/2/library/pprint.html
you can use f-string (python 3.6 or newer) or format
using f-string:
print(f'{item1:width} {item2:width}')
using format:
print('{:10} {:10}'.format(item1, item2))
10 is column width vary as needed

replace item1, item2 with your data
Hello,

making:

a = ('User ID', 'Hits', {'1982641': 10, '105350': 9, '1008313': 7, '2073270': 11, '2073279':10})

you can use c = sorted(a[2].iteritems(), key=lambda (k,v): (v,k)) to sorted the dict and then you can print using @Larz60+ comments.
Below is my code, Logs file contains hundred thousands of values few of mentioned in previous post. As i have tried your method but unable to fetch it.

fobj = open("logs", "r")
text = fobj.read()
dict = re.findall(r'.*user_id=(\d*)', text, re.M)

test = {}

for item in dict:
  try:
    test[item] += 1
  except:
    test[item] = 1


print('User ID', 'Hits', test)
(Nov-09-2018, 11:27 AM)Larz60+ Wrote: [ -> ]you can use f-string (python 3.6 or newer) or format
using f-string:
print(f'{item1:width} {item2:width}')
using format:
print('{:10} {:10}'.format(item1, item2))
10 is column width vary as needed

replace item1, item2 with your data

Hi Larz60,

I followed your point but unable to get exact output what is need. I have paste my code in previous post. Please look into it.