Search code examples
pythondictionary-comprehension

Oneliner to create a dictionary from two lists in Python


I want to create this dictionary, but using one liner.

{'apple_last_6kg':'buy','mango_last_6kg':'buy','banana_last_6kg':'buy',
 'apple_last_4kg':'buy','mango_last_4kg':'buy','banana_last_4kg':'buy',
 'apple_last_3kg':'buy','mango_last_3kg':'buy','banana_last_3kg':'buy',
 'apple_last_kg':'buy','mango_last_kg':'buy','banana_last_kg':'buy'}

This is what I initially tried and got the error, though {**{'a':1},**{'b':2}} works perfectly and gives {'a':1,'b':2}, but using this formulation in dictionary comprehension gives error.:

dic2 = {**{i+'_last_'+time:'buy' for i in ['apple','mango','banana']} for time in ['kg','3kg','4kg','6kg']}
print(dic2)
File "<ipython-input-238-9332e6a46412>", line 29
    dic2 = {**{i+'_last_'+time:'buy' for i in ['apple','mango','banana']} for time in ['kg','3kg','4kg','6kg']}
          ^
SyntaxError: dict unpacking cannot be used in dict comprehension

I solved this like below, but I would like to have a one liner dictionay-comprehension like solution. Any suggestions?

# This solution is unelegant, so I don't want to use this.
dic2 = [{i+'_last_'+j:'buy' for i in ['apple','mango','banana']} for j in ['kg','3kg','4kg','6kg']]

new_dic = {}
for d in dic2:
    new_dic.update(d)
print(new_dic)
{'apple_last_3kg': 'buy','apple_last_4kg': 'buy','apple_last_6kg': 'buy',
 'apple_last_kg': 'buy','banana_last_3kg': 'buy','banana_last_4kg': 'buy',
 'banana_last_6kg': 'buy','banana_last_kg': 'buy','mango_last_3kg': 'buy',
 'mango_last_4kg': 'buy','mango_last_6kg': 'buy','mango_last_kg': 'buy'}

Solution

  • dict.fromkeys(
        (i+'_last_'+j for j in ['6kg','4kg','3kg','kg'] for i in ['apple','mango','banana']),
        "buy"
    )
    

    See this classmethod here.