简体   繁体   English

从Python中的列表元素创建字典

[英]Create dictionary from list elements in Python

I have a list similar to the following: 我有一个类似于以下内容的列表:

my_list =
    [(1, 'item_19'),
     (2, 'item_20'),
     (3, 'item_21'),
     (4, 'item_22'),
     (5, 'item_23'),
     (6, 'item_24'),
     (7, 'item_25'),
     (8, 'item_26'),
     (9, 'item_27'),
     (10, 'item_28'),
     (11, 'item_29'),
     (12, 'item_30'),
     (13, 'item_31'),
     (14, 'item_32'),
     (15, 'item_33'),
     (16, 'item_34'),
     (17, 'item_35')]

I would like to make a dictionary of each element of the list, ie 1:'item_19',2:'item_20' 我想为列表中的每个元素制作一个字典,即1:'item_19',2:'item_20'

I currently do this: 我目前正在这样做:

list_1 = [l[0] for l in my_list]
list_2 = [l[1] for l in my_list] 

and then zip the two lists 然后压缩两个列表

my_dict = dict(zip(list_1,list_2))

However there are more than a million element in my_list , so is this the best way to do this, or is there a quicker/more optimal way to do it(Memory wise). 但是, my_list中有超过一百万个元素,所以这是执行此操作的最佳方法,还是有一种更快/更优化的方法(在内存方面)。

To put this in context, I want a lookup table to check if elements in my_dict already exist in a different dictionary my_dict_old 为了说明这一点,我希望查找表检查my_dict元素my_dict已存在于其他字典my_dict_old

The builtin dict function takes a list of tuples, which is exactly what you are providing: 内置的dict函数接受一个元组列表,这正是您所提供的:

>>> list_foo = [(1, 'item_1'), (2, 'item_2')]
>>> dict(list_foo)
{1: 'item_1', 2: 'item_2'}

If all you need to do is check for an item's existence, consider using set , as i in my_set is much faster than i in my_dict.values() , see the Python documentation on performance for more info. 如果您需要做的只是检查项目的存在,请考虑使用set ,因为i in my_set中的i in my_dict.values()i in my_dict.values()有关性能的更多信息, 请参见Python文档 On my machine, for example, a lookup in a haystack of 10k entries is .443s with dict.values() , vs <.000s for set . 例如,在我的机器上,在1万个条目的.443s的查找为.443s ,而.443s dict.values() <.000s对于set If you need to associate values with the entries, then use a dictionary, otherwise use a set. 如果需要将值与条目关联,则使用字典,否则使用集合。 For a more in-depth examination of lists vs. dictionaries (and also sets for the most part), refer to this answer . 要更深入地检查列表与字典(以及大多数情况下也包含字典),请参阅此答案

dict accepts list of tuples, so you can just use your original list: dict接受元组列表,因此您可以使用原始列表:

my_dict = dict(my_list)

And you are actually doing the same thing while calling zip 而且您实际上在调用zip在做同样的事情

Also, if all keys are numbers and are not huge you can put all of them into array. 另外,如果所有键都是数字并且不是很大,则可以将它们全部放入数组。 Index would be the key. 索引将是关键。 Though this solution depends on the actual task and might not be useful in some cases 尽管此解决方案取决于实际任务,在某些情况下可能无用

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

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