Skip to content

Instantly share code, notes, and snippets.

@GeorgySk
Created October 27, 2018 22:08
Show Gist options
  • Save GeorgySk/554cac3e3586a01db512f895eeaa4001 to your computer and use it in GitHub Desktop.
Save GeorgySk/554cac3e3586a01db512f895eeaa4001 to your computer and use it in GitHub Desktop.
Example of how to print aligned a table from a list of dicts
from operator import itemgetter
from typing import (Any,
Dict,
Iterable,
Iterator,
List,
Sequence)
def max_length(objects: Iterable[Any]) -> int:
"""Returns maximum string length of a sequence of objects"""
strings = map(str, objects)
return max(map(len, strings))
def values_max_length(dicts: Sequence[Dict[str, Any]],
*,
key: str) -> int:
"""Returns maximum string length of dicts values for specific key"""
return max_length(map(itemgetter(key), dicts))
def to_aligned_data(dicts: Sequence[Dict[str, Any]],
*,
keys: List[str],
sep: str = ' ') -> Iterator[str]:
"""Prints a sequence of dicts in a form of a left aligned table"""
lengths = (values_max_length(dicts, key=key)
for key in keys)
format_string = sep.join(map('{{:{}}}'.format, lengths))
for row in map(itemgetter(*keys), dicts):
yield format_string.format(*row)
if __name__ == '__main__':
data = [{'Key': '1',
'Title': 'Salvation.S02E11.HDTV.x264-KILLERS',
'Seeds': '262',
'Leechers': '19'},
{'Key': '2',
'Title': 'Salvation.S02E13.WEB.x264-TBS[ettv]',
'Seeds': '229',
'Leechers': '25'},
{'Key': '3',
'Title': 'Salvation.S02E08.HDTV.x264-KILLERS',
'Seeds': '178',
'Leechers': '21'},
{'Key': '4',
'Title': 'Salvation.S02E01.HDTV.x264-KILLERS',
'Seeds': '144',
'Leechers': '11'},
{'Key': '5',
'Title': 'Salvation.S02E09.HDTV.x264-SVA[ettv]',
'Seeds': '129',
'Leechers': '14'}]
keys = ['Key', 'Title', 'Seeds', 'Leechers']
print(*to_aligned_data(data, keys=keys),
sep='\n')
# 1 Salvation.S02E11.HDTV.x264-KILLERS 262 19
# 2 Salvation.S02E13.WEB.x264-TBS[ettv] 229 25
# 3 Salvation.S02E08.HDTV.x264-KILLERS 178 21
# 4 Salvation.S02E01.HDTV.x264-KILLERS 144 11
# 5 Salvation.S02E09.HDTV.x264-SVA[ettv] 129 14
keys = ['Title', 'Leechers']
print(*to_aligned_data(data, keys=keys),
sep='\n')
# Salvation.S02E11.HDTV.x264-KILLERS 19
# Salvation.S02E13.WEB.x264-TBS[ettv] 25
# Salvation.S02E08.HDTV.x264-KILLERS 21
# Salvation.S02E01.HDTV.x264-KILLERS 11
# Salvation.S02E09.HDTV.x264-SVA[ettv] 14
keys = ['Key', 'Title', 'Seeds', 'Leechers']
print(*to_aligned_data(data, keys=keys, sep=' ' * 5),
sep='\n')
# 1 Salvation.S02E11.HDTV.x264-KILLERS 262 19
# 2 Salvation.S02E13.WEB.x264-TBS[ettv] 229 25
# 3 Salvation.S02E08.HDTV.x264-KILLERS 178 21
# 4 Salvation.S02E01.HDTV.x264-KILLERS 144 11
# 5 Salvation.S02E09.HDTV.x264-SVA[ettv] 129 14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment