Python如何将字典列表转换为元组列表 [英] Python how to convert a list of dict to a list of tuples

查看:1797
本文介绍了Python如何将字典列表转换为元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的字典列表:

I have a list of dict that looks like this:

list=[{u'hello':['001', 3], u'word':['003', 1], u'boy':['002', 2]}, 
     {u'dad':['007', 3], u'mom':['005', 3], u'honey':['002', 2]} ] 

我需要在列表上进行迭代,以创建如下这样的元组列表:

What I need is to iterate on my list in order to create list of tuples like this:

new_list=[('hello','001', 3), ('word','003',1), ('boy','002', 2)
           ('dad','007',3), ('mom', '005', 3), ('honey','002',2)]

注意!带有零的数字('001',003'...等等)必须视为字符串.

NOTE! the numbers with the zeros ('001',003'... and so on) must be considerated as a string.

有人可以帮助我吗?

推荐答案

您可以为此使用列表理解:

You can use list comprehension for that:

new_list = [(key,)+tuple(val) for dic in list for key,val in dic.items()]

在这里,我们遍历所有dic色调in list.对于每个dic字典,我们对其.items()进行迭代,并提取keyval ue,然后使用(key,)+val为其构造一个元组.

Here we iterate over all dictonaries in list. For every dictionary we iterate over its .items() and extract the key and value and then we construct a tuple for that with (key,)+val.

值是否为字符串无关紧要:列表理解只是复制引用,因此,如果原始元素为Foo s,则它们仍为Foo s.

Whether the values are strings or not is irrelevant: the list comprehension simply copies the reference so if the original elements were Foos, they remain Foos.

最后请注意,字典是无序的,因此顺序不确定.但是,如果在字典d2之前出现字典d1,则第一个元素的所有元素将在列表的元组之前放置在列表中.但是并不确定每个字典的元组顺序.

Finally note that the dictionaries are unordered, so the order is undetermined. However if a dictionary d1 occurs before a dictionary d2, all the elements of the first will be placed in the list before the tuples of the latter. But the order of tuples for each individual dictionary is not determined.

这篇关于Python如何将字典列表转换为元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆