我正在尝试使用我必须从一个元素和一个列表创建的列表创建一个字典。有没有更简单的方法来做到这一点,因为它更有效率?
这是我到目前为止所做的事情
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
答案 0 :(得分:1)
>>> chars = ['a', 'b', 'c']
>>> single = 1
>>>
>>> {key: [(single, key)] for key in chars}
{'a': (1, 'a'), 'c': (1, 'c'), 'b': (1, 'b')}
>>>
这样,您无需创建merged_list
,也可以直接跳过创建词典。
答案 1 :(得分:1)
您可以跳过中间列表,直接进行映射:
first_element = 1
list2 = ['a', 'b', 'c']
merged_dict = {item: [(first_element, item)] for item in list2}