Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (Retired) Dictionaries Introduction To Dictionaries

David Kan
David Kan
4,058 Points

For the first challenge, I do not understand where to even start.

Write a function named members that takes two arguments, a dictionary and a list of keys. Return a count of how many of the keys are in the dictionary. I do not understand how to solve this..

Matthew Leung
Matthew Leung
1,434 Points

My code works in the workspace but does not pass the challenge?

def members(my_dict,my_list):
  count = 0

  for item in my_list:
    try:
      my_dict[item]
      count += 1
    except KeyError:
      count += 0
  return count

20 Answers

David Kan
David Kan
4,058 Points

Finally did it.

some_dict = {'a': 1, 'b': 2, 'c': 3}

key_list = ['a', 'b', 'd']

def members(some_dict, key_list):

  counts = 0

  for item in key_list:

    if item in some_dict.keys():

      counts += 1

  return counts

Thank you for your help.

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Awesome, congrats on working through it!

where did the concept of the '.keys()' part come from? I would not have figured that out on my own, but using that makes it tremendously easier... and how exactly does '.keys()' work? What are the major purposes and or uses for it?

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Jamison Imhoff If you look at dict with either dir() or help(), you'll see .keys() defined. .keys() gives you an iterable of all of the key names in a dictionary. If you're just looping, the following are equivalent:

for key in my_dict:

for key in my_dict.keys():

The first is probably slightly faster because it doesn't have to do the processing that .keys() requires on the dict. You'd only notice this on a massively large dictionary, though, so don't worry about it until you explicitly need it.

Ok that makes more sense...

So what would be an example then when it would be more beneficial to use the .keys() ? Something like when you need to see all of the key names? I am just trying to fully grasp when I would be better off using .keys() instead of just not bothering adding that to the variable (if that makes sense...)

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

If you have a really large dictionary, .keys() isn't a list, it's a generator, which plays much more nicely with memory. Or, yes, if you want to get just a list of the key names for some other purpose.

Could you please walk me through the process of arriving at that answer? Im totally lost :( Thanks alot in advance :)

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

I added some more comments to the starter file, so hopefully we'll have less confusion on this in the future. Thanks for the input , everyone!

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

So I'm going to give a dictionary like:

some_dict = {'a': 1, 'b': 2, 'c': 3}`

And a list like:

key_list = ['a', 'b', 'd']

Tell me how many of the keys in key_list are in the some_dict dictionary.

Jeff Everhart
Jeff Everhart
21,732 Points

Awesome, Kenneth! That's why you guys rock. All of the Treehouse teachers really make it known that they care about student success by being open and responsive to student feedback. Keep up the awesome sauce, now I'm back to your Python course (which is very well designed, btw)...

Hi David,

Try to break the problem down into the parts that you can do.

  • Write a function named members that takes two arguments, a dictionary and a list of keys.
  • Return a count of how many of the keys are in the dictionary.

It's asking how many of the keys that are in list, can also be found in the dictionary?

Try writing the code you know, and post it here inside backticks with the python language specified for proper syntax highlighting (reference the Markdown Cheatsheet below).

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

You did Python Basics, right? So you have to write a function. members = (some_dict, key_list) isn't a function, it's putting a tuple into a variable. Start with writing the function.

def members(some_dict, key_list):

OK, so now what? How would you hold onto a count of the number of keys that are good? How would you loop through the keys in the list? How would you check to see if they key is in the dictionary? Remember what keyword sends information back out of a function?

guys , i just found a bug in this example.

my_dict = {'apples': 1, 'bananas': 2, 'coconuts': 3} my_list = ['apples', 'coconuts', 'grapes', 'strawberries']

def members(my_dict, my_list) : return 2

! Congrats! You completed the challenge!

i ended up here to help understand the prompt for this challenge, and now that i have working code, i'm unable to get it to be accepted in the challenge prompt.

this code below runs fine in my workspace and returns 2 as the count (which is correct), but when i paste it into the code challenge i get the error "word_count() missing 1 required positional argument: 'key_list'"

my_dict = {'i': 1, 'am': 2, 'that': 3}
key_list = ['i', 'am', 'what']

def word_count(my_dict, key_list):
  count = 0
  for word in key_list:
    if word in my_dict.keys():
      count += 1
  print(count)
  return count

word_count(my_dict, key_list)

does anyone know why this would be? it doesn't make sense to me...

Hi Amanda,

It looks like your code is written to pass this challenge.

Your code is good but the function needs to be named members. Also, just paste in the function - don't need the other code setting up a list and dictionary and don't need to call it.

Hope this helps,

Cheers

Hey Robert, thanks for the reply. My code is written for the Word Count challenge, however. The two sets of code do work in similar ways, though.

It just confuses me that the code works fine in the workspace, but when I paste the exact same code into the code challenge I get an error.

EDIT: Just realized this thread relates to the Membership challenge you referenced, not the Word Count challenge. No wonder I'm still having trouble! Sorry about that.

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Your code is good but missing one fairly important part. What about words that aren't in the dictionary yet? They need to get a count of 1.

Also, word_count won't get a key_list argument, only the string to count the words in.

I can help get you started without spoiling too much.

  • Write a function named members that takes two arguments, a dictionary and a list of keys
def members(some_dict, key_list):
  # your function logic goes here  
David Kan
David Kan
4,058 Points

So I got...

some_dict = {'a': 1, 'b': 2, 'c': 3}

key_list = ['a', 'b', 'd']

members = (some_dict, key_list)

but I don't understand how to return a count of how many of the keys are in the dictionary.

Ya i was kinda confused on the wording of the question too. As soon as i saw what Kenneth put for some_dict and key_list it cleared it up.

Matthew Bingham
Matthew Bingham
11,927 Points

Is it not possible to use the len method in this instance?

def members(my_dict, my_list):
  return len(my_dict.keys())

Getting "Expected 2, got 6." but would be a much more elegant solution (if it worked)!

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

No, you can't do it with just len() and my_dict.keys() because you have to check against the key names in my_list.

Kevin Fricovsky
PLUS
Kevin Fricovsky
Courses Plus Student 14,460 Points

I am wondering what other's opinions are on using list comprehensions as a solution? I came up with the following:

my_dict = {'a': 1, 'b': 2, 'c': 3}
my_list = ['a', 'b', 'd', 'e']

def members(my_dict, my_list):
  return len([dictkeys for dictkeys in my_dict.keys() if dictkeys in my_list])
Jeff Everhart
Jeff Everhart
21,732 Points

Hello all, thanks for the questions in this forum. You comments and suggestions got me where I needed to be. To be honest, I was confused on the wording of the question: Write a function named members that takes two arguments, a dictionary and a list of keys. Return a count of how many of the keys are in the dictionary.

The noun "the keys" in the second sentence could refer to either the keys in the dictionary or the keys in my_list. Kenneth, the extra starter text is a bit helpful, but you might just consider revising the initial prompt to read something like this: Return a count of how many of the keys in my_list are ALSO in the dictionary.

That way it is clear that we are not just looping over my_dict to count those keys, but rather checking the keys in my_dict against the keys in my_list. Sorry for the nit-picky suggestion, but every once in awhile the English teacher in me makes an appearance. Thanks for the good stuff Treehouse team! Keep it up and happy coding! :)

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Don't apologize! I think your suggestion is very solid. I'm about to update the prompt.

Tomasz Necek
PLUS
Tomasz Necek
Courses Plus Student 7,028 Points

I did it but, could you write - one more time - the easiest way to solve this problem, i can't say, that I understand it in 100 %

Tomas Pavlik
Tomas Pavlik
26,726 Points

I'figured out another way of solving this problem, without using the keys()method:

def members(my_dict, my_keys):
    count = 0
    for item in my_keys:
        for key in my_dict:
        if key == item:
           count += 1
    return count 

Hopefully it is pythonically correct :-)

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Your solution is OK but you don't need two for loops.

Mike Tribe
Mike Tribe
3,827 Points
def members(aDict, keyList):
  memcount = 0
  for key in keyList:
    if key in aDict:
      memcount += 1
  return memcount

2

def members(some_dict, key_list):

  counts = 0

  for item in key_list:

    if item in some_dict.keys():

      counts += 1

  return counts

yaaah this one works for me

Neil Gordon
Neil Gordon
8,823 Points

https://wiki.python.org/moin/DictionaryKeys

in addition to the explanations it may help to read over keys