Flash Sale: Flat 70% + Addl. 25% Off on all Courses | Use Coupon DS25 in Checkout | Offer Expires In

  Enroll Now

Working with Dictionaries

Dictionaries have a method called get that takes a key and a default value as arguments. If the key is found in the dictionary, get returns the corresponding value, else returns the default value.

d = {"apples" : 2, "bananas" : 3, "carrots" : 12}
print(d.get("oranges", 0))

It prints 0, because "oranges" isn't a key available and 0 is the default value.

If you use a for loop to traverse in the dictionary, it traverses over the keys and using which you can iterate over the values as well.

for fruit in d:
    print(fruit)

It prints the keys present in d.

INSTRUCTIONS
  • Define a function with the name dict_func that takes one argument (assume string) and returns a dictionary with keys as words in the string and values as the number of times those words occur in the string.

  • You can assume that the string will always have at least one word.

Sample Input -

dict_func('the quick brown fox jumps over the lazy dog')

Sample Output -

{'the': 2,
 'quick': 1,
 'brown': 1,
 'fox': 1,
 'jumps': 1,
 'over': 1,
 'lazy': 1,
 'dog': 1}

No hints are availble for this assesment

Answer is not availble for this assesment


Note - Having trouble with the assessment engine? Follow the steps listed here

Loading comments...