简体   繁体   中英

Convert a dictionary into a list of tuples

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM