Split list of names into alphabetic dictionary, in Python
List.
['Chro开发者_开发技巧me', 'Chromium', 'Google', 'Python']
Result.
{'C': ['Chrome', 'Chromium'], 'G': ['Google'], 'P': ['Python']}
I can make it work like this.
alphabet = dict()
for name in ['Chrome', 'Chromium', 'Google', 'Python']:
character = name[:1].upper()
if not character in alphabet:
alphabet[character] = list()
alphabet[character].append(name)
It is probably a bit faster to pre-populate the dictionary with A-Z, to save the key check on every name, and then afterwards delete keys with empty lists. I'm not sure either is the best solution though.
Is there a pythonic way to do this?
Anything wrong with this? I agree with Antoine, the oneliner solution is rather cryptic.
import collections
alphabet = collections.defaultdict(list)
for word in words:
alphabet[word[0].upper()].append(word)
I don't know if it's Pythonic, but it's more succinct:
import itertools
def keyfunc(x):
return x[:1].upper()
l = ['Chrome', 'Chromium', 'Google', 'Python']
l.sort(key=keyfunc)
dict((key, list(value)) for (key,value) in itertools.groupby(l, keyfunc))
EDIT 2 made it less succinct than previous version, more readable and more correct (groupby
works as intended only on sorted lists)
精彩评论