Split a list of names in an alphabetical dictionary in Python

List.

['Chrome', 'Chromium', 'Google', 'Python']

Result.

{'C': ['Chrome', 'Chromium'], 'G': ['Google'], 'P': ['Python']}

I can make it work as follows.

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’s probably a little faster to pre-populate the AZ dictionary to save a key check for each name, and then delete keys with empty lists. I am not sure if this is the best solution.

Is there a pythonic way to do this?

+3
source share
2 answers

Is there something 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)
+9
source

I don't know if this is Pythonic, but it is more concise:

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 , , (groupby )

+5

Source: https://habr.com/ru/post/1772261/


All Articles