[英]How to create a dictionary from a list of strings with same key, value in python
I have a list of strings with no duplicate elements and I need to generate a dictionary with elements of this list as key and values of this dictionary.我有一个没有重复元素的字符串列表,我需要用这个列表的元素作为这个字典的键和值来生成一个字典。
List: file_names = ['a', 'bb', 'ccc', 'ad', 'rsb']
列表:
file_names = ['a', 'bb', 'ccc', 'ad', 'rsb']
Desired dictionary:想要的字典:
file_names = {'a': 'a', 'bb':'bb', 'ccc': 'ccc', 'ad': 'ad', 'rsb':'rsb'}
I want each element of list be as the key and also exactly have that element as it's value for that key.我希望列表的每个元素都作为键,并且也完全具有该元素作为该键的值。 What is the best (most fast) way for generating such a dictionary in python specifically python 2?
在python中特别是python 2中生成这样的字典的最佳(最快)方法是什么?
Please consider using a set
instead if all you wish to do is check if an element is in a collection.请考虑使用
set
,而不是全部,如果你希望做的是检查元素是否是一个收藏。 This gives you O(1)
complexity for membership tests.这为成员资格测试提供了
O(1)
复杂度。 You can convert a list
to a set
by doing您可以通过执行将
list
转换为set
file_names = set(['a', 'bb', 'ccc', 'ad', 'rsb'])
file_names = set(file_names)
Then, you can check for membership by simply doing然后,您只需执行以下操作即可检查会员资格
if file_name in file_names:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.