[英]How to convert this dictionary into a list of tuples?
I have this dictionary; 我有这本字典。
Dict={1: ('John', 129L, 37L), 2: ('James', 231L, 23L)}
I want to convert it into a list of tuples that look like this; 我想将其转换为如下所示的元组列表;
List=[(1, 'John', 129L, 37L), (2, 'James', 231L, 23L)]
I tried Dict.items() but it did not yield the desirable results but was close. 我尝试了Dict.items(),但没有得到理想的结果,但是很接近。 What is the correct solution?
什么是正确的解决方案?
I am using Python 2.7 我正在使用Python 2.7
Using list comprehension : 使用列表理解 :
>>> d = {1: ('John', 129L, 37L), 2: ('James', 231L, 23L)}
>>> [(key,) + value for key, value in d.iteritems()]
[(1, 'John', 129L, 37L), (2, 'James', 231L, 23L)]
BTW, the order of items in the generated list is not guaranteed. 顺便说一句,不能保证所生成列表中项目的顺序。 Because
dict
is a unordered mapping. 因为
dict
是无序映射。
If you want the result to be ordered by keys, use sorted
: 如果希望按键对结果进行排序,请使用
sorted
:
>>> [(key,) + value for key, value in sorted(d.iteritems())]
[(1, 'John', 129L, 37L), (2, 'James', 231L, 23L)]
my_dict = {1: ('John', 129L, 37L), 2: ('James', 231L, 23L)}
print [(k,) + my_dict[k] for k in my_dict]
# [(1, 'John', 129L, 37L), (2, 'James', 231L, 23L)]
Sorted by keys version: 按键版本排序:
print [(k,) + my_dict[k] for k in sorted(my_dict)]
Explanation: 说明:
(k,) + my_dict[k]
is extending the tuple (k,)
(Yes, a single item, with comma, inside parens is a tuple) by concatenating with the values corresponding to the key k
(k,) + my_dict[k]
通过与键k
对应的值进行级联来扩展元组(k,)
(是,单项,用逗号表示,在括号内是一个元组)
Using map: 使用地图:
map(lambda x: (x,) + Dict[x] , Dict.keys())
Output: 输出:
[(1, 'John', 129L, 37L), (2, 'James', 231L, 23L)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.