我有一个字典,其中包含键作为单词,值包含数字。
| A | B | C |
|------------+------------+-----------------|
1| Submitting | Lookup | Selling Windows |
|------------+------------+-----------------|
2| 13/07/2016 | 13/07/2016 | 27/07/2016 |
3| 14/07/2016 | 27/07/2016 | 13/07/2016 |
4| 15/07/2016 | 27/07/2016 | |
5| 16/07/2016 | 27/07/2016 | |
6| 17/07/2016 | 27/07/2016 | |
7| 18/07/2016 | 27/07/2016 | |
8| 19/07/2016 | 27/07/2016 | |
9| 20/07/2016 | 27/07/2016 | |
10| 21/07/2016 | 27/07/2016 | |
11| 22/07/2016 | 27/07/2016 | |
12| 23/07/2016 | 27/07/2016 | |
13| 24/07/2016 | 27/07/2016 | |
14| 25/07/2016 | 27/07/2016 | |
15| 26/07/2016 | 27/07/2016 | |
16| 27/07/2016 | 27/07/2016 | |
如何将键和值打印成两列,其中第二列的宽度为最长键,所有值都打印在右侧?
d = dict(bag.items())
我试过这个:
10 potatoes
8 tomato
5 onion
3 plate
2 ham
1 meat
但我必须找到一种方法来设置右侧的值,因此在键和值之间建立适当的空格。
答案 0 :(得分:2)
建立最大宽度,format字符串:
mkey = max(map(len, (map(str, bag.keys()))))
mval = max(map(len, (map(str, bag.values()))))
for k, v in bag.items():
print(' {:>{}} {:>{}}'.format(k, mkey, v, mval))
答案 1 :(得分:0)
我是这样做的:
bag = {'tomato': 15, 'onion': 3,'potatoes': 7, 'ham': 2}
bag_values = []
longest = ""
for k in bag:
if len(k) > len(longest):
longest = k
longest_v = ""
for k, v in bag.items():
bag_values.append(str(v))
for value in bag_values:
if len(value) > len(longest_v):
longest_v = value
space = " "
a = (len(7*space)+len(longest_v)+len(longest))
for k, v in bag.items():
c = len(longest) - len(k)
b = len(longest_v) - len(str(v))
print((3+b)*space + str(v) + (4+c)*space + k)