【问题标题】:What's an elegant way to create a dictionary from another dictionary's keys and an array of values?从另一个字典的键和值数组创建字典的优雅方法是什么?
【发布时间】:2010-06-29 15:07:36
【问题描述】:

如何使用另一个字典的键和值数组创建另一个字典?

我想过这样做:

zipped = zip(theExistingDict.keys(), arrayOfValues)
myNewDict = dict(zipped)

但是,这并不完全有效,arrayOfValues 中的每个值都与结果字典中的任意键配对。我无法控制arrayOfValues 中的哪个元素与theExistingDict.keys() 中的哪个键配对。

theExistingDict 看起来像这样:

{u'actual bitrate': 4, u'Suggested Bitrate': 3, u'title': 2, u'id': 1, u'game slot': 0}

arrayOfValues 看起来像这样:

1.0, u'GOLD_Spider Solitaire', u'Spider\\nSolitaire', 120000.0, 120000.0

所以:我希望 arrayOfValues[0] 映射到 game slot(因为在字典中它的值为 0)。

有没有一种简单而优雅的方法来做到这一点?

【问题讨论】:

  • 嗯,你想要哪个订单?那么键和值之间有什么联系呢?
  • theExistingDict.keys() 会以任意顺序为您提供密钥。您可能必须以某种方式对其进行排序。只有你知道哪些键值对属于一起。
  • @SilentGhost - 请看我上面的编辑。

标签: python dictionary


【解决方案1】:

由于您现有的字典本身包含有关列表中元素位置的信息:您可以这样做:

>>> exist = {u'title': 2, u'actual bitrate': 4, u'id': 1, u'game slot': 0, u'Suggested Bitrate': 3}
>>> l = [1.0, u'GOLD_Spider Solitaire', u'Spider\\nSolitaire', 120000.0, 120000.0]
>>> dict((k, l[v]) for k, v in exist.iteritems())
{u'Suggested Bitrate': 120000.0, u'game slot': 1.0, u'actual bitrate': 120000.0, u'id': u'GOLD_Spider Solitaire', u'title': u'Spider\\nSolitaire'}

或在 py3k/python 2.7+ 中:

>>> {k: l[v] for k, v in exist.items()}
{'Suggested Bitrate': 120000.0, 'game slot': 1.0, 'actual bitrate': 120000.0, 'id': 'GOLD_Spider Solitaire', 'title': 'Spider\\nSolitaire'}

【讨论】:

  • 非常优雅 - 这是我一直在寻找的解决方案,谢谢!
【解决方案2】:

正如其他人所提到的,字典中没有定义任何顺序。 python 文档说,“键和值以非随机的任意顺序列出,在 Python 实现中有所不同,并且取决于字典的插入和删除历史。”

如果您希望使用将项目添加到字典中的原始顺序,您可以尝试寻找保留此顺序的字典的替代实现 - 例如http://www.voidspace.org.uk/python/odict.html

【讨论】:

    【解决方案3】:

    根据上述 cmets,theExistingDict 的字典可能不是您要查找的结构。

    您可能对ordered dictionary 感兴趣。

    另请参阅"What’s the way to keep the dictionary parameter order in Python?" 的答案

    【讨论】:

      【解决方案4】:

      也许更像:

      from operator import itemgetter
      zip( array_of_values, [ a for a, _ in sorted(existing_dict.iteritems(), key=itemgetter(1)) ] )
      

      如果您想将索引与整数匹配,可以进一步修改,可能与未使用的值...

       zipped = [ (k, a) for i, a in enumerate(array_of_values) for k, v in existing_dict.iteritems() if i == v ]
       new_dict = dict(zipped)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-10-05
        • 2010-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-09
        • 2023-01-11
        • 1970-01-01
        相关资源
        最近更新 更多