简体   繁体   English

打印特定格式的字典

[英]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} 我有这样的字典: {('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 mydict就是这样

{('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): 使用itertools.groupby (需要注意的一件事是,您必须先进行排序,因为当键值更改时, groupby将创建一个新的组):

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. ps我不确定您的任务是什么,但是您可能不应该将元组用作字典中的键。

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. 您可以使用groupby按密钥长度分组并打印每个分组。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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