python - printing a dictionary with specific format -
i done project , want print results. have dictionary this: {('a',): 4, ('b',): 5, ('c', 'd'): 3, ('e', 'f'): 4, ('g', 'h'): 3, ('i',): 3}
the key in pair key-value 1 element , in others 2 or three. , want print in format, elements 1 key in 1 line, elements 2 keys in new line etc...
(elem,) (elem1, elem2, ..., elem_n)
i tried this:
itemdct //my dict result = [itemdct] csv_writer = csv.writer(sys.stdout, delimiter=';') row = [] itemdct in result: key in sorted(itemdct.keys()): row.append("{0}:{1}".format(key, itemdct[key])) csv_writer.writerow(row)
but output in 1 line.
('a',):3;('b',):4;('c', 'd'):3;('e', 'f'):3;......
mydict this
{('a',): 3, ('b', 'c'): 3, ....}
and result this
[{('a',): 3, ('b', 'c'): 3,.....}]
thank in advance..
edit: want output this:
('a',):3;('c',):4;('c',):5;('d',):6;('e',):3 ('a', 'c'):3;('b', 'd'):3;('c', 'd'):4
you can sort items of dictionary according key length. can use groupby group key length , print each group.
def printdict(mydict): itertools import groupby def sortfunc(item): return len(item[0]) sorteditems = sorted(mydict.items(), key=sortfunc) groups = groupby(sorteditems, sortfunc) _, group in groups: print( ';'.join('%s:%s' % entry entry in group))
output:
>>> printdict({('a',): 4, ('b',): 5, ('c', 'd'): 3, ('e', 'f'): 4, ('g', 'h'): 3, ('i',): 3}) ('a',):4;('i',):3;('b',):5 ('e', 'f'):4;('g', 'h'):3;('c', 'd'):3
Comments
Post a Comment