我有以下列表和字典:
list = [[1,2,2],[2,3,3],[3,4,4]
dict = {1:[], 2:[], 3:[]}
让我们说我想将所有继续dict [keys]的值附加到各自的键中,以便:
dict = {1:[2,2], 2:[3,3], 3:[4,4]}
我尝试使用多个循环来完成此任务。但是,每当我这样做时,所有值都会被搜索并同时附加到每个dict [key]。任何帮助将不胜感激!
答案 0 :(得分:4)
l = [[1,2,2],[2,3,3],[3,4,4]]
# last key wins
d = {sublist[0]:sublist[1:] for sublist in l}
print(d)
您可以从列表元素构造字典。不要使用list
或dict
作为名称,它们会影响内置插件。
sublist[0]
是第一个元素,sublist[1:]
是l中每个项目的其余元素。
有关此处使用的语法的更多信息:PEP 274: Dict Comprehensions
输出:
{1: [2, 2], 2: [3, 3], 3: [4, 4]} # last key wins (no duplicates present)
如果您还需要合并,可以使用:
# merging keys into values as list of sublists
l = [[2,2,2],[2,3,3],[3,4,4]]
d1 = {}
for sub in l:
# creates dict of { key: [ [int,...], [int,...] ], ... } for same keys
d1.setdefault(sub[0],[]).append(sub[1:])
或扁平化:
# merging keys into values as flattened list
d2 = {}
for sub in l:
# creates dict of { key: [ int,...,int,... ], ... } for same keys
d2.setdefault(sub[0],[]).extend(sub[1:])
输出:
{2: [[2, 2], [3, 3]], 3: [[4, 4]]} # merging keys into values as list of sublists
{2: [2, 2, 3, 3], 3: [4, 4]} # merging keys into values as flattened list
对于合并我使用dict.setdefault()你可能想看看collections.defaultdict(),我确信它更适合。