如何将列表转换为键和值相同的字典?

时间:2016-09-24 18:29:51

标签: python python-3.x dictionary

这是基于这个问题:python convert list to dictionary

提问者提供以下内容:

l = ["a", "b", "c", "d", "e"]
     

我想将此列表转换为   字典如:

d = {"a": "b", "c": "d", "e": ""}

虽然石斑鱼配方非常有趣并且我一直在“玩”它,然而,我想做的是,不像那个提问者想要的输出词典,我想转换一个像字符串一样的列表将上面的一个放入字典中,其中所有值和键都相同。例如:

d = {"a": "a", "c": "c", "d": "d", "e": "e"}

我该怎么做?

修改

实施代码:

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()

2 个答案:

答案 0 :(得分:5)

您可以将同一个列表压缩在一起:

dict(zip(l, l))

或使用词典理解:

{i: i for i in l}

后者更快:

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

即使对于大型序列也是如此:

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

答案 1 :(得分:2)

你可以像这样使用dict-comprehension

l = ["a", "b", "c", "d", "e"]
d = {s: s for s in l}