import operator
pay = {}
lowestPay={}
averagePay={}
pay["Developers"]=[35,22,18,36]
pay["Designers"]=[25,65,24,45]
pay["Testers"]=[34,52,12,32]
userInput=int(input("How would you like the menu to be sorted?\n1 for Dictionary keys sorted in alphabetical order\n2 for Sort each list of employee’s pay rates from highest to lowest\n3 for Lowest pay level in each list sorted from highest to lowest\n4 for Average pay per department sorted from highest to lowest"))
if userInput == 1:
for key,value in pay.items():
sortedDictionary = sorted(pay)
print (sortedDictionary)
if userInput == 2:
for key,value in pay.items():
value.sort()
value.reverse()
print(key,value)
if userInput == 3:
for key,value in pay.items():
value.sort()
lowestPay [key]=value.pop()
lowestPaySorted = sorted(pay.items(),key=operator.itemgetter(1),reverse=True)
print (lowestPay)
if userInput == 4:
for key,value in pay.items():
average = sum(value)/len(value)
averagePay [key]=(average)
averagePaySorted = sorted(averagePay.items(),key=operator.itemgetter(1),reverse=True)
for keys in averagePaySorted:
print (keys)
for value in averagePaySorted[keys]:
print (value,':',cars[keys][value])
上面我有我的排序列表程序。我需要打印字典averagePaySorted
。我是新手,所以我不知道该怎么办,因为你可以看到我试图从其他一些页面尝试打印这个但是我收到了这个错误:
... line 33, in <module>
for value in averagePaySorted[keys]:
TypeError: list indices must be integers, not tuple
我不知道这意味着我需要它看起来像这样
B
color : 3
speed : 60
A
color : 2
speed : 70
但是这是从另一个论坛获取以节省时间
答案 0 :(得分:3)
要打印字典,请查看pprint。如,
print pformat(averagePaySorted)
或者,更完整的例子:
from pprint import pformat
mydict = {'a': 1, 'b': 2, c: [4, 5, 6]}
print pformat(mydict)
pprint
处理嵌套,如,
print pformat(mydict, width=1)
产生
{'a': 1,
'b': 2,
'c': [4,
5,
6]}
答案 1 :(得分:1)
您遇到的问题是因为此方案中的键是元组(键,值)
要打印此内容,请使用与
类似的内容for key,value in list:
print key, ':', value