简体   繁体   English

如何将字典追加到循环列表中

[英]How to append dictionary to a list in loop

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) . 每个元组都有一个指定的格式,如(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 aa 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'}]

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. 此外,有> 10000元组。 Declaring that many dictionaries is just not done. 声明许多字典都没有完成。

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'] ? 另外,如果可以,我们可以通过它的关键值访问每个字典,比如finalDictList[0]['key1']吗?

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: 首先, 列表理解 ,然后是zip方法,最后是dict方法,用于从元组列表中构建字典:

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]

After that, the value of the final variable is: 之后, 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, ie: 此外,您可以使用列表中字典的位置和您要查找的键来获取某个字典的元素,即:

>>> final[0]['key1']
'a1'

Use zip to combine a pre-defined list of key names with each tuple in your input list, then pass the results to dict to make them into dicts. 使用zip将预定义的键名列表与输入列表中的每个元组组合,然后将结果传递给dict以使其成为dicts。 Wrap the whole thing in a list comprehension to process them all in one batch: 将整个事物包含在列表理解中,以便在一个批处理中处理它们:

keys = ('key1', 'key2', 'key3', 'key4', 'key5')
finalDictList = [dict(zip(keys, values)) for values in tupleList]

I'm not sure I see why you need to convert everything to a dictionary, when you've already got a list of tuples. 当你已经有一个元组列表时,我不确定为什么你需要将所有内容转换为字典。

>>> tupleList = [('a1', 'b1', 'c1', 'd1', 'e1'),
...              ('a2', 'b2', 'c2', 'd2', 'e2'),
...              ('a10000', 'b10000', 'c10000', 'd10000', 'e100000')]
>>> [x[1] for x in tupleList]
['b1', 'b2', 'b10000']

Using Python's list comprehension syntax, you can get a list of all the n-th elements of each tuple. 使用Python的列表推导语法,您可以获得每个元组的所有第n个元素的列表。

If the fields are fix you can do this: 如果字段已修复,您可以执行以下操作:

fields = ['key1', 'key2', 'key3', 'key4', 'key5']

newList = [dict(zip(fields, vals)) for vals in oldList]

If as you say you have a lot of entries, remember that python has namedtuples : 如果你说你有很多条目,请记住python有namedtuples

>>> tupleList = [('a1', 'b1', 'c1', 'd1', 'e1'),
...              ('a2', 'b2', 'c2', 'd2', 'e2'),
...              ('a10000', 'b10000', 'c10000', 'd10000', 'e100000')]
>>>
>>> from collections import namedtuple
>>> fv = namedtuple('fivevals', ('key1', 'key2', 'key3', 'key4', 'key5'))
>>> tuplelist = [fv(*item) for item in tupleList]
>>> 
>>> tuplelist[0].key1
'a1'
>>>

Namedtuples can be accesed by key but at the same time they are lightweight and require no more memory than regular tuples. Namedtuples可以通过键加入,但同时它们是轻量级的,并且不需要比常规元组更多的内存。

finalDictList = []
for t in tupleList:
    finalDictList.append({
        'key1': t[0],
        'key2': t[1],
        'key3': t[2],
        'key4': t[3],
        'key5': t[4],
    })

Also, if that is possible, can we access each dictionary by it's key values, say, like finalDictList[0]['key1']? 另外,如果可以,我们可以通过它的关键值访问每个字典,比如finalDictList [0] ['key1']吗?

Absolutely, that is exactly how you would do it. 当然,这正是你要做的。

from itertools import izip

keys = ['key1', 'key2', 'key3', 'key4', 'key5']
finalDictList = [dict(izip(names, x)) for x in tupleList]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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