2

Given a dictionary like this:

dic = {(7, 3): 18.51, (1, 3): 18.751, (5, 6): 34.917, (9, 8): 18.9738}

I want to convert it to a list of tuples like this:

my_list = [(7, 3, 18.51), (1, 3, 18.751), (5, 6, 34.917), (9, 8, 18.9738)]

I could have used a loop but I wonder if there is a neat way to do so instead of loops.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Don
  • 393
  • 3
  • 12

1 Answers1

5

Simply use list(..) on some generator:

my_list = list(key+(val,) for key,val in dic.items())

This works since:

  • list(..) takes as input an iterable and converts it to a list; and
  • key+(val,) for key,val dic.items() is a generator that takes a pair of key-values of dic and transforms it into a tuple appending the val to the key.

Since we use a generator for a list, we can simplify this with list comprehension:

my_list = [key+(val,) for key,val in dic.items()]

Finally mind that the order in which the tuples occur is not fixed this is because the order how a dict stores elements is not fixed as well.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555