简体   繁体   English

如何从python中具有相同键和值的字符串列表创建字典

[英]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.

相关问题 Python从具有key:value字符串的列表中创建字典 - Python create dictionary from a list that has key:value strings 如何在 Python 中的字典列表中使用另一个键列表中的值在字典中创建一个新键? - How to create a new key in dictionary with value from another key list from a list of dictionary in Python? 如何从字典中的字典迭代和 append 键值对并将具有相同键的值存储到列表 python - How to iterate and append key value pairs from a dictionary within a dicionary and storing values with same key into a list python 创建一个 python 字典,其中值是字符串列表 - create a python dictionary where the value is a list of strings 如何基于字典键的相同值创建列表 - How to create a list based on same value of a dictionary key 如何从列表中创建一个字典,只包含键列表和键值对(Python)? - How to create a dictionary from a list with a list of keys only and key-value pairs (Python)? Python-如果字符串列表不在字典键中,则从字典列表中删除字典 - Python - Remove dictionary from list of dictionaries if list of strings not in dictionary key 如何从 python 中的字符串列表创建字典或 json? - how to create dictionary or json from list of strings in python? 如何使用字典中的相同键创建值列表 - How to create a list of values with the same key from a dictionary 如何从每个键的键列表中初始化 python 中的字典以具有相同的初始值? - How can I initialize a dictionary in python from a list of keys for each key to have the same initial value?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM