def count_first_letter(names):
a={}
for i in names.keys():
if i[0] in a.keys():
#print(i)
#print(i[0])
#print(len(names[i]))
#print(a[i[0]])
a[i[0]]+=len(names[i])
else:
#print(i)
#print(i[0])
#print(names[i])
#print(len(names[i]))
a.update({i[0]:len(names[i])})
return a
Thank you all for sharing your solutions! I found this challenge very difficult and approached it in a too complicated way (e. g. tried to loop through the whole dictionary and not just through the keys) and it helps a lot to see how other people approached it!
Just found this different way to do this exercise, different from given solution I mean if anyone is interested.
def count_first_letter(names):
new_dict = {}
for key, value in names.items():
if key[0:1] not in new_dict:
new_dict[key[0:1]] = len(value)
else:
new_dict[key[0:1]] = new_dict[key[0:1]] + len(value)
return new_dict
def count_first_letter(names):
ind = []
for key, value in names.items():
length = len(value)
while length > 0:
ind.append(key[0])
length -= 1
return count_values(ind)
def count_values(list):
new_list = []
count = 1
ind = []
for elem in list:
if elem not in ind:
new_list.append(elem)
new_list.append(list.count(elem))
ind.append(elem)
return convert_to_dic(new_list)
def convert_to_dic(list):
dic = {}
for i in range(0, (len(list)-1), 2):
dic.update({list[i]:list[i+1]})
return dic
After redoing this after a year I came up with this solution based on something I read somewhere on codecademy but I can’t remember where on defaultdict !
def count_first_letter(names):
letter_count = {}
for key, value in names.items():
if key[0] in letter_count.keys():
letter_count[key] += len(value)
else:
letter_count[key[0]] = len(value)
return letter_count
I’ve also used an else statement but it worked with the “not in” in boolean operator
def count_first_letter(names):
initials_count = {}
for key in names:
if key[0] not in initials_count:
initials_count[key[0]] = len(names[key])
else:
initials_count[key[0]] += len(names[key])
return initials_count
def count_first_letter(names):
result = {}
key_letters = [key[0] for key in names.keys()]
values_letters = [len(value) for value in names.values()]
for index, key in enumerate(key_letters):
if key not in result.keys():
result.update({key:values_letters[index]})
else:
result[key] += values_letters[index]
return result