Python Forum
Why is this function printing the number of keys in a dictionary?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why is this function printing the number of keys in a dictionary?
#3
(Sep-16-2019, 08:13 PM)woooee Wrote: Can't tell from your code because it isn't formatted, but it looks like dictionary is only declared within the function, so is not defined anywhere outside the function. i.e. for the print statement. Also, the function is never called and so will never execute, and there is no reason to sort the list as it has only one item, a dictionary.

My bad, didn't even notice. Here it is:

def dictKeysOnly (dictionary):
>>>lst = [{dictionary}]
>>>lst = sorted(lst)
>>>return (lst)
>>>print("List in ascending order: ",sorted(dictionary))

Edit: I'm not sure how to indent, but everything under the function is indented once.

When I try to call the function, here is what I get back.

dictKeysOnly({"kelly","amber","sophia","henry","zak"})

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-25723a87e72e> in <module>
----> 1 dictKeysOnly({"kelly","amber","sophia","henry","zak"})

<ipython-input-3-93a6185952c3> in dictKeysOnly(dictionary)
1 def dictKeysOnly (dictionary):
----> 2 lst = [{dictionary}]
3 lst = sorted(lst)
4 return (lst)
5 print("List in ascending order: ",sorted(dictionary))

TypeError: unhashable type: 'set'

What do you mean by it's not defined outside the function, and how would I fix that? And how would I give it a reason to sort the list.
Reply


Messages In This Thread
RE: Why is this function printing the number of keys in a dictionary? - by mafr97 - Sep-16-2019, 09:05 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  create empty sets for keys in a dictionary and add values to the set naughtysensei 1 2,538 Nov-03-2020, 08:32 AM
Last Post: DeaD_EyE
  get method within max function for a dictionary Blanchdog 3 1,924 Jul-03-2020, 05:55 PM
Last Post: ndc85430
  How to use value in dictionary as arguments in function gabejohnsonny21 6 3,795 Apr-22-2020, 04:53 PM
Last Post: deanhystad
  Printing a number sequence not working properly deepsen 6 3,070 Oct-12-2019, 07:43 PM
Last Post: deepsen
  printing data from dictionary kiki1113 4 51,312 Nov-20-2017, 04:43 PM
Last Post: heiner55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020