【问题标题】:How to convert a list to a dictionary where both key and value are the same?如何将列表转换为键和值都相同的字典?
【发布时间】:2016-09-24 18:29:50
【问题描述】:

这是基于这个问题: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()

【问题讨论】:

  • 这样一个结构的意义何在?
  • 我想要一个包含单词所有可能排列的字典,然后在我的脚本中运行。我发现将字母大写的所有可能排列放入列表中是最简单的,但是,我需要将其放入 dict 中以简化我需要做的事情。
  • 如果你想要所有排列,看看这个stackoverflow.com/questions/8306654/…
  • @Pablo 很容易弄清楚如何获得字母大写的排列,但是,我只需要弄清楚如何将输出(列表)放入字典中。
  • 创建一个空的dict 就像h = {} 然后你可以做[h[x] = x for x in my_permutation_list]。我仍然不明白你需要字典做什么。 --edit: 或者你可以像 Martijn Pieters 那样使用字典理解。

标签: python python-3.x dictionary


【解决方案1】:

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

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

【讨论】:

  • 时间很有趣——这是python 2还是3?
  • @DavidZwicker:Python 3.6,在 2.7 上重现(对比度仍然更大)。
【解决方案2】:

您可以像这样使用dict-comprehension

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多