如何从一个具有相同键和值的字符串列表中创建一个字典在Python中。

huangapple go评论82阅读模式
英文:

How to create a dictionary from a list of strings with same key, value in python

问题

我有一个没有重复元素的字符串列表,我需要生成一个字典,其中这个列表的元素作为键,同时作为字典的值。

列表:
file_names = ['a', 'bb', 'ccc', 'ad', 'rsb']

期望的字典:

file_names = {'a': 'a', 'bb': 'bb', 'ccc': 'ccc', 'ad': 'ad', 'rsb': 'rsb'}

我希望列表的每个元素都作为键,并且确切地拥有该元素作为该键的值。在Python中,特别是Python 2中,生成这样一个字典的最快方式是什么?

英文:

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']

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?

答案1

得分: 4

请考虑使用 set,如果您只想检查元素是否在集合中。这可以为成员测试提供 O(1) 复杂度。您可以通过以下方式将一个 list 转换为一个 set

file_names = set(['a', 'bb', 'ccc', 'ad', 'rsb'])
file_names = set(file_names)

然后,您可以通过以下方式简单地检查成员身份:

if file_name in file_names:
英文:

Please consider using a set instead if all you wish to do is check if an element is in a collection. This gives you O(1) complexity for membership tests. You can convert a list to a set by doing

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:

huangapple
  • 本文由 发表于 2020年1月6日 15:01:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/59607942.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定