简体   繁体   中英

printing a dictionary with specific format

i am already done with my project and i want to print my results. i have a dictionary like this: {('a',): 4, ('b',): 5, ('c', 'd'): 3, ('e', 'f'): 4, ('g', 'h'): 3, ('i',): 3}

the key in some pair key-value is one element and in some others is two or three. and i want to print it in this format, the elements with one key in one line, the elements with two keys in a new line etc...

(elem,)
(elem1, elem2, ..., elem_n)

i tried this:

itemdct //my dict
result = [itemdct]
csv_writer = csv.writer(sys.stdout, delimiter=';')
row = []
for itemdct in result:
    for key in sorted(itemdct.keys()):
        row.append("{0}:{1}".format(key, itemdct[key]))
csv_writer.writerow(row)

but my output is like this in one line.

('a',):3;('b',):4;('c', 'd'):3;('e', 'f'):3;......

mydict is like this

{('a',): 3, ('b', 'c'): 3, ....}

and the result is like this

[{('a',): 3, ('b', 'c'): 3,.....}]

thank you in advance..

edit: i want my output to be like this:

('a',):3;('c',):4;('c',):5;('d',):6;('e',):3
('a', 'c'):3;('b', 'd'):3;('c', 'd'):4

Using itertools.groupby (one thing to note is that you have to sort first, because groupby will create a new group when the key value changes):

from itertools import groupby
d = {('a',): 4, ('b',): 5, ('c', 'd'): 3, ('e', 'f'): 4, ('g', 'h'): 3, ('i',): 3}
for i, g in groupby(sorted(d.items(), key = lambda k: len(k[0])), lambda k: len(k[0])):
  print(';'.join('%s:%s' %(k,v) for k,v in g))

## -- End pasted text --
('a',):4;('i',):3;('b',):5
('e', 'f'):4;('g', 'h'):3;('c', 'd'):3

ps I'm not sure what your assignment is, but you should probably not be using tuples as keys in a dictionary.

There is two steps to this. The first is to sort out what entry goes into what line, the other is to print those lines.

from collections import defaultdict

d = {('a',): 4, ('b',): 5, ('c', 'd'): 3, ('e', 'f'): 4, ('g', 'h'): 3, ('i',): 3}

keysize = defaultdict(list)
for key in d:
    keysize[len(key)].append("{}:{}".format(key, h[key]))

for size, line in keysize.iteritems():
    print ", ".join(line)

You can sort the items of your dictionary according to their key length. The you can use groupby to group by key length and print each group.

def printDict(myDict):
    from itertools import groupby
    def sortFunc(item):
        return len(item[0])

    sortedItems = sorted(myDict.items(), key=sortFunc)
    groups = groupby(sortedItems, sortFunc)
    for _, group in groups:         
        print( ';'.join('%s:%s' % entry for 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM