cizwiz
cizwiz

Reputation: 15

How to Print Dictionaries In Python

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])

Above I have my program for sorting lists. I need to print the dictionary averagePaySorted. I am quite new to this so I am not to sure what to do as you can see I tried to attempt printing this from some other pages but I got this error:

  ... line 33, in <module>
    for value in averagePaySorted[keys]:
TypeError: list indices must be integers, not tuple

I have no idea what that means I need it to out look something like this

B
color : 3
speed : 60
A
color : 2
speed : 70

but this was taken from a different forum to save time

Upvotes: 1

Views: 129

Answers (2)

ron rothman
ron rothman

Reputation: 18148

To print a dictionary, check out pprint. E.g.,

print pformat(averagePaySorted)

Or, a more complete example:

from pprint import pformat
mydict = {'a': 1, 'b': 2, c: [4, 5, 6]}
print pformat(mydict)

  1. pprint handles nesting, and
  2. advanced options are available.

E.g.,

print pformat(mydict, width=1)

produces:

{'a': 1,
 'b': 2,
 'c': [4,
       5,
       6]}

Upvotes: 3

Cristopher
Cristopher

Reputation: 323

The problem you have is because keys on this scenario is a tuple (key, value)

To print this, use something similar to

for key,value in list:
  print key, ':', value

Upvotes: 1

Related Questions