Home > Back-end >  dictionary where key is first letter of element in list and values are element
dictionary where key is first letter of element in list and values are element

Time:10-22

Given a list of lowercase strings named mystrings, create and return a dictionary whose keys are the unique first characters of the strings and whose values are lists of words beginning with those characters, in the same order that they appear in the list of strings. Ignore case: you can assume that all words are lowercase. A sample list of strings is given below, but your code should work on any list of strings of any length. You do not have to write a function.

mystrings = ["banana", "xylophone", "duck", "carriage", "bandana", "diamond", "cardinal"]

output is {'b': ['banana', 'bandana'], 'x': ['xylophone'], 'd': ['duck', 'diamond'],

'c': ['carriage', 'cardinal']}

I have tried using a loop but am getting stuck.

CodePudding user response:

Use a loop and dict's setdefault:

mystrings = ["banana", "xylophone", "duck", "carriage", "bandana", "diamond", "cardinal"]

out = {}
for word in mystrings:
    out.setdefault(word[0], []).append(word)

Output:

{'b': ['banana', 'bandana'],
 'x': ['xylophone'],
 'd': ['duck', 'diamond'],
 'c': ['carriage', 'cardinal']}

CodePudding user response:

One-liner loop:

mystrings_dict = {k: [w for w in mystrings_list if w[0] == k] for k in set([w[0] for w in mystrings_list])}

Traditional loop:

mystrings_list = ["banana", "xylophone", "duck", "carriage", "bandana", "diamond", "cardinal"]
mystrings_dict = dict()
for word in mystrings_list:
    firstletter = word[0]  # 0th element of string is first letter
    if firstletter in mystrings_dict:
        mystrings_dict[firstletter].append(word)
    else:
        mystrings_dict[firstletter] = [word]

Results:

print(mystrings_dict)
>> {'b': ['banana', 'bandana'], 'x': ['xylophone'], 'd': ['duck', 'diamond'], 'c': ['carriage', 'cardinal']}

CodePudding user response:

You will look for every word in words, if the first letter of a word is not in the solution dictionary you will create a list associated to that letter, if not, that means that exist a list in that letter (in the dictionary) with at least a word inside, then you add the new word to that list.

words =  ["banana", "xylophone", "duck", "carriage", "bandana", "diamond", "cardinal"]

sol={}
for w in words:
    if w[0] not in sol:
        sol[w[0]] = []
    sol[w[0]].append(w)

print(sol)

CodePudding user response:

Alternatively, you can try the collections module, defaultdict:

from collections import defaultdict
dd = defaultdict(list)
mystrings = ["banana", "xylophone", "duck", "carriage", "bandana", "diamond", "cardinal"]
for word in mystrings:
    first = word[0]
    dd[first].append(word)

    
print(dd)
defaultdict(<class 'list'>, {'b': ['banana', 'bandana'], 'x': ['xylophone'], 'd': ['duck', 'diamond'], 'c': ['carriage', 'cardinal']})
  • Related