如何在循环中将字典追加到列表 [英] How to append dictionary to a list in loop
问题描述
我可以使用元组列表形式的大量数据.每个元组都有指定的格式,例如(a, b, c, d, e)
.元组列表如下:
I have at my disposal huge amount of data, in the form of a list of tuples. Each tuple has a specified format like (a, b, c, d, e)
. The list of tuples looks like:
tupleList = [('a1', 'b1', 'c1', 'd1', 'e1'),
('a2', 'b2', 'c2', 'd2', 'e2'),
...
('a10000', 'b10000', 'c10000', 'd10000', 'e100000')]
我想要的是将每个元组转换为字典,并将字典附加到最终的字典列表中.所有这些都可以循环完成吗?最终的词典列表应如下所示:
What I want is, to convert each of these tuples to a dictionary, and append the dictionary to a a final list of dictionaries. Can all this be done in a loop? The final list of dictionaries should look like:
finalDictList = [{'key1': 'a1', 'key2': 'b1', 'key3': 'c1', 'key4': 'd1', 'key5': 'e1'},
{'key1': 'a2', 'key2': 'b2', 'key3': 'c2', 'key4': 'd2', 'key5': 'e2'},
{'key1': 'a3', 'key2': 'b3', 'key3': 'c3', 'key4': 'd3', 'key5': 'e3'},
...
{'key1': 'a10000', 'key2': 'b10000', 'key3': 'c10000', 'key4': 'd10000', 'key5': 'e10000'}]
元组的格式是固定的.我想将余音,字典中每个键的值与所有其他键进行比较.这就是为什么将元组转换为字典对我有意义的原因.如果设计范例本身看起来不对,请纠正我.此外,还有> 10000个元组.声明许多字典只是没有完成.
The format of the tuples is fixed. I want to compare afterwords, value of each key of a dictionary with all others. This is why the conversion of tuple to dictionary made sense to me. Please correct me if the design paradigm itself seems wrong. Also, there are >10000 tuples. Declaring that many dictionaries is just not done.
反正有没有将字典添加到循环列表中的列表?另外,如果可能的话,我们是否可以按键值访问每个字典,例如finalDictList[0]['key1']
?
Is there anyway to append dictionary to a list in a loop? Also, if that is possible, can we access each dictionary by it's key values, say, like finalDictList[0]['key1']
?
推荐答案
我们将混合使用三个重要的概念,以使此代码真正的小巧美观.首先是列表理解,然后是 dict 方法,从元组列表中构建字典:
We're going to mix three important concepts to make this code really small and beautiful. First, a list comprehension, then, the zip method, and finally, the dict method, to build a dictionary out of a list of tuples:
my_list = [('a1', 'b1', 'c1', 'd1', 'e1'), ('a2', 'b2', 'c2', 'd2', 'e2')]
keys = ('key1', 'key2', 'key3', 'key4', 'key5')
final = [dict(zip(keys, elems)) for elems in my_list]
之后,final
变量的值为:
>>> final
[{'key3': 'c1', 'key2': 'b1', 'key1': 'a1', 'key5': 'e1', 'key4': 'd1'},
{'key3': 'c2', 'key2': 'b2', 'key1': 'a2', 'key5': 'e2', 'key4': 'd2'}]
此外,您还可以使用字典在列表中的位置以及所需的键来获取某个字典的元素,即:
Also, you can get elements of a certain dictionary using the position of the dictionary in the list and the key you're looking for, i.e.:
>>> final[0]['key1']
'a1'
这篇关于如何在循环中将字典追加到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!