[英]How to convert a list to a dictionary where both key and value are the same?
This is based on this question: python convert list to dictionary这是基于这个问题: python convert list to dictionary
The asker provides the following:提问者提供以下信息:
l = ["a", "b", "c", "d", "e"]
I want to convert this list to a dictionary like:
我想将此列表转换为字典,例如:
d = {"a": "b", "c": "d", "e": ""}
While the grouper recipe is quite interesting and I have been "playing" around with it, however, what I would like to do is, unlike the output dictionary wanted by that asker, I would like to convert a list with strings like the one above into a dictionary where all values and keys are the same.虽然石斑鱼的食谱很有趣,我一直在“玩”它,但是,我想做的是,与该提问者想要的输出字典不同,我想转换一个带有字符串的列表,如上面的放入所有值和键都相同的字典中。 Example:
例子:
d = {"a": "a", "c": "c", "d": "d", "e": "e"}
How would I do this?我该怎么做?
Edit :编辑:
Implementation code:实现代码:
def ylimChoice():
#returns all permutations of letter capitalisation in a certain word.
def permLet(s):
return(''.join(t) for t in product(*zip(s.lower(), s.upper())))
inputList = []
yesNo = input('Would you like to set custom ylim() arguments? ')
inputList.append(yesNo)
yes = list(permLet("yes"))
no = list(permLet("no"))
if any(yesNo in str({y: y for y in yes}.values()) for yesNo in inputList[0]):
yLimits()
elif any(yesNo in str({n: n for n in no}.values()) for yesNo in inputList[0]):
labelLocation = number.arange(len(count))
plot.bar(labelLocation, list(count.values()), align='center', width=0.5)
plot.xticks(labelLocation, list(count.keys()))
plot.xlabel('Characters')
plot.ylabel('Frequency')
plot.autoscale(enable=True, axis='both', tight=False)
plot.show()
You can just zip the same list together:您可以将相同的列表压缩在一起:
dict(zip(l, l))
or use a dict comprehension:或使用字典理解:
{i: i for i in l}
The latter is faster:后者更快:
>>> from timeit import timeit
>>> timeit('dict(zip(l, l))', 'l = ["a", "b", "c", "d", "e"]')
0.850489666001522
>>> timeit('{i: i for i in l}', 'l = ["a", "b", "c", "d", "e"]')
0.38318819299456663
This holds even for large sequences:这甚至适用于大序列:
>>> timeit('dict(zip(l, l))', 'l = range(1000000)', number=10)
1.28369528199255
>>> timeit('{i: i for i in l}', 'l = range(1000000)', number=10)
0.9533485669962829
You can use a dict-comprehension like this:您可以使用这样的字典理解:
l = ["a", "b", "c", "d", "e"]
d = {s: s for s in l}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.