python,将字典拆分为元组列表


dictionary = {1: ['a', 'b'], 2: ['a'], 3: ['b', 'c']}

我希望这本字典在元组列表中,如下所示:输出:

[(1, 'a'),(1, 'b'),(2, 'a'),(3, 'b'),(3, 'c')]

请帮帮我!!!

你可以通过理解来做到这一点:

[(x, z) for x, y in dictionary.items() for z in y]

或扩展:

out = []
for x, y in dictionary.items():
for z in y:
out.append((x, z))

dictionary={1:[‘a','b'],2:[‘a'],3:[‘b','c']}

list_of_tuples = []
for k,v_list in dictionary.items():
for v in v_list:
list_of_tuples.append((k,v))
list_of_tuples

最新更新