问题描述:

I have a tuple that contains random words such as

words = ("Apple","Charlie","Papa","Uniform","Tango","Echo","Romeo")

and I want to sort these into a dictionary like

dict = {"A": "Apple","C": "Charlie", "P": "Papa", "U" : "Uniform"....}

I know I need to initialize the dictionary and create a for loop to look through the tuple, but I don't know how to sort by letter.

网友答案:

You can use dict comprehensions.

>>> words = ("Apple","Charlie","Papa","Uniform","Tango","Echo","Romeo")
>>> mydict = {value[0]: value for value in words}
>>> print(mydict)
{'A': 'Apple', 'C': 'Charlie', 'E': 'Echo', 'P': 'Papa', 'R': 'Romeo', 'U': 'Uniform', 'T': 'Tango'}

It will not be ordered, but if you need that pass it through

>>> OrderedDict(sorted(mydict.items()))
网友答案:

For the case you've mentioned, it's easy:

d = {}
for word in words:
    d[word[0]] = word

Of course, the normal caveats apply (dicts aren't ordered so there's no filtering involved, if "Adam" and "Apple" are both in your input, only the second will find its way into the output, etc). To take care of the latter problem, you might want to consider a collections.defaultdict:

from collections import defaultdict
d = defaultdict(list)
for word in words:
    d[word[0]].append(word)

which will leave you with a dict of characters mapped to a list. And, once you have this, if you really want it to be "sorted" by key, you can do that with a collections.OrderedDict after the fact:

odict = OrderedDict()
for key in sorted(d):  # d is the defaultdict from the last step.
    odict[key] = d[key]
相关阅读:
Top