Best way to use list comprehension to create a constant dict of labels and abbreviations dependent upon the number of entries

Question:

I am not as new to Python but I struggle quite a lot with list comprehension, I cannot seem to wrap my head around it. I am learning but would not mind advice on how to solve something in my programme I am writing in an optimal fashion. I have a constant list of labels and corresponding list of abbreviations that the user sets from the command line (or reverts to hardcoded defaults from another .py file) and then remains constant throughout the run.

However, I do not know how to write the list comprehension to include a variable amount of inputs without hard coding or using a for loop. For example:

ALPHA = ['alpha', 'beta', 'zeta']
A     = ['a', 'b', 'z']

A_DICT = {'1': {'label': ALPHA[0], 'abbrev': A[0]},
          '2': {'label': ALPHA[1], 'abbrev': A[1]},
          '3': {'label': ALPHA[2], 'abbrev': A[2]}}

How can I create A_DICT using list comprehension if this indeed the best the way to create the dict please? The number of entries in ALPHA and A can change depending on user input. I am sorry if this is low quality/duplicate, I am trying to get my head around list comprehension but it does not quite sink in whereas other aspects of Python do with little issue.

Asked By: 1ae1_NADPH

||

Answers:

You can do with dictionary comprehension.

With an assumption that ALPHA and A are equal length.

In [1]: {
     ...:     str(index): {"label": item, "abbrev": A[index]}
     ...:     for index, item in enumerate(ALPHA, start=1)
     ...: }
Out[1]: 
{'1': {'label': 'alpha', 'abbrev': 'a'},
 '2': {'label': 'beta', 'abbrev': 'b'},
 '3': {'label': 'zeta', 'abbrev': 'z'}}
Answered By: Rahul K P

It sounds like what you could use python builtin zip, to iterate over two iterables at once.

If you need those numbers as keys in the final dict ('1', '2', '3'), you wrap the whole zip generator in enumerate.

A_DICT = {str(i): {'label': l, 'abbrev': a} for i, (l, a) in enumerate(zip(ALPHA, A))}

Another option, assuming the lists are of equal length, it may be simpler to solely produce the index.

A_DICT = {str(i): {'label': ALPHA[i], 'abbrev': A[i]} for i in range(len(ALPHA))}

However, I have doubts about the data structure here in general, though I don’t fully understand your specific application. If you always know the keys in each individual dict (‘label’, and ‘abbrev’) why not just make a dict that is callable by label to get the abbrev (or the other way around)?

SOME_DICT = {label: abbrev for label, abbrev in zip(ALPHA, A)}

# {'alpha': 'a', 'beta': 'b', 'zeta': 'z'}

Edit: As pointed out in comments, above way is same as:

SOME_DICT = dict(zip(ALPHA, A))
Answered By: crunker99
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.