[英]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: 只需在某些生成器上使用
list(..)
:
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; 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
. key+(val,) for key,val dic.items()
是生成器,它接受dic
的一对键值并将其转换为将val
附加到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. 最后要注意的是,元组的出现顺序不是固定的,这是因为
dict
存储元素的顺序也不固定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.