-1

I am trying to create a dictionary from using a list that I have to create from one element and a list. Is there an easier way to do this so it is much more efficient?

This is what I have done so far

first_element = 1
list2 = ['a', 'b', 'c']

merged_list = []
for item in list2: 
    merged_tuple = (first_element, item)
    merged_list.append(merged_tuple)        

print (merged_list)
>>> [(1, 'a'), (1, 'b'), (1, 'c')]

merged_dict = {value: [(key, value)] for (key, value) in merged_list}
print (merged_dict)
>>> {'a': [(1, 'a')], 'c': [(1, 'c')], 'b': [(1, 'b')]} #desired result
Cryssie
  • 3,047
  • 10
  • 54
  • 81

2 Answers2

1

This can be more pythonic by using a dictionary comprehension:

>>> chars = ['a', 'b', 'c']
>>> single = 1
>>> 
>>> {key: [(single, key)] for key in chars}
{'a': (1, 'a'), 'c': (1, 'c'), 'b': (1, 'b')}
>>> 

In this way, you don't need to create merged_list, and can skip directly to creating your dictionary.

Community
  • 1
  • 1
Christian Dean
  • 22,138
  • 7
  • 54
  • 87
1

You could skip the intermediate list and just make the mappings directly:

first_element = 1
list2 = ['a', 'b', 'c']

merged_dict = {item: [(first_element, item)] for item in list2}
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271