Login using Social Account
     Continue with GoogleLogin using your credentials
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
.
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}
Taking you to the next exercise in seconds...
Want to create exercises like this yourself? Click here.
Loading comments...